babylon.max.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775
  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. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. /**
  31. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  32. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  33. */
  34. var EffectFallbacks = /** @class */ (function () {
  35. function EffectFallbacks() {
  36. this._defines = {};
  37. this._currentRank = 32;
  38. this._maxRank = -1;
  39. }
  40. /**
  41. * Removes the fallback from the bound mesh.
  42. */
  43. EffectFallbacks.prototype.unBindMesh = function () {
  44. this._mesh = null;
  45. };
  46. /**
  47. * Adds a fallback on the specified property.
  48. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  49. * @param define The name of the define in the shader
  50. */
  51. EffectFallbacks.prototype.addFallback = function (rank, define) {
  52. if (!this._defines[rank]) {
  53. if (rank < this._currentRank) {
  54. this._currentRank = rank;
  55. }
  56. if (rank > this._maxRank) {
  57. this._maxRank = rank;
  58. }
  59. this._defines[rank] = new Array();
  60. }
  61. this._defines[rank].push(define);
  62. };
  63. /**
  64. * Sets the mesh to use CPU skinning when needing to fallback.
  65. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  66. * @param mesh The mesh to use the fallbacks.
  67. */
  68. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  69. this._mesh = mesh;
  70. if (rank < this._currentRank) {
  71. this._currentRank = rank;
  72. }
  73. if (rank > this._maxRank) {
  74. this._maxRank = rank;
  75. }
  76. };
  77. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  78. /**
  79. * Checks to see if more fallbacks are still availible.
  80. */
  81. get: function () {
  82. return this._currentRank <= this._maxRank;
  83. },
  84. enumerable: true,
  85. configurable: true
  86. });
  87. /**
  88. * Removes the defines that shoould be removed when falling back.
  89. * @param currentDefines defines the current define statements for the shader.
  90. * @param effect defines the current effect we try to compile
  91. * @returns The resulting defines with defines of the current rank removed.
  92. */
  93. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  94. // First we try to switch to CPU skinning
  95. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  96. this._mesh.computeBonesUsingShaders = false;
  97. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  98. var scene = this._mesh.getScene();
  99. for (var index = 0; index < scene.meshes.length; index++) {
  100. var otherMesh = scene.meshes[index];
  101. if (!otherMesh.material) {
  102. continue;
  103. }
  104. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  105. continue;
  106. }
  107. if (otherMesh.material.getEffect() === effect) {
  108. otherMesh.computeBonesUsingShaders = false;
  109. }
  110. else {
  111. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  112. var subMesh = _a[_i];
  113. var subMeshEffect = subMesh.effect;
  114. if (subMeshEffect === effect) {
  115. otherMesh.computeBonesUsingShaders = false;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. var currentFallbacks = this._defines[this._currentRank];
  124. if (currentFallbacks) {
  125. for (var index = 0; index < currentFallbacks.length; index++) {
  126. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  127. }
  128. }
  129. this._currentRank++;
  130. }
  131. return currentDefines;
  132. };
  133. return EffectFallbacks;
  134. }());
  135. BABYLON.EffectFallbacks = EffectFallbacks;
  136. /**
  137. * Options to be used when creating an effect.
  138. */
  139. var EffectCreationOptions = /** @class */ (function () {
  140. function EffectCreationOptions() {
  141. }
  142. return EffectCreationOptions;
  143. }());
  144. BABYLON.EffectCreationOptions = EffectCreationOptions;
  145. /**
  146. * Effect containing vertex and fragment shader that can be executed on an object.
  147. */
  148. var Effect = /** @class */ (function () {
  149. /**
  150. * Instantiates an effect.
  151. * An effect can be used to create/manage/execute vertex and fragment shaders.
  152. * @param baseName Name of the effect.
  153. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  154. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  155. * @param samplers List of sampler variables that will be passed to the shader.
  156. * @param engine Engine to be used to render the effect
  157. * @param defines Define statements to be added to the shader.
  158. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  159. * @param onCompiled Callback that will be called when the shader is compiled.
  160. * @param onError Callback that will be called if an error occurs during shader compilation.
  161. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  162. */
  163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  164. if (samplers === void 0) { samplers = null; }
  165. if (defines === void 0) { defines = null; }
  166. if (fallbacks === void 0) { fallbacks = null; }
  167. if (onCompiled === void 0) { onCompiled = null; }
  168. if (onError === void 0) { onError = null; }
  169. var _this = this;
  170. /**
  171. * Unique ID of the effect.
  172. */
  173. this.uniqueId = 0;
  174. /**
  175. * Observable that will be called when the shader is compiled.
  176. */
  177. this.onCompileObservable = new BABYLON.Observable();
  178. /**
  179. * Observable that will be called if an error occurs during shader compilation.
  180. */
  181. this.onErrorObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called when effect is bound.
  184. */
  185. this.onBindObservable = new BABYLON.Observable();
  186. this._uniformBuffersNames = {};
  187. this._isReady = false;
  188. this._compilationError = "";
  189. this.name = baseName;
  190. if (attributesNamesOrOptions.attributes) {
  191. var options = attributesNamesOrOptions;
  192. this._engine = uniformsNamesOrEngine;
  193. this._attributesNames = options.attributes;
  194. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  195. this._samplers = options.samplers;
  196. this.defines = options.defines;
  197. this.onError = options.onError;
  198. this.onCompiled = options.onCompiled;
  199. this._fallbacks = options.fallbacks;
  200. this._indexParameters = options.indexParameters;
  201. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  202. if (options.uniformBuffersNames) {
  203. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  204. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  205. }
  206. }
  207. }
  208. else {
  209. this._engine = engine;
  210. this.defines = defines;
  211. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  212. this._samplers = samplers;
  213. this._attributesNames = attributesNamesOrOptions;
  214. this.onError = onError;
  215. this.onCompiled = onCompiled;
  216. this._indexParameters = indexParameters;
  217. this._fallbacks = fallbacks;
  218. }
  219. this.uniqueId = Effect._uniqueIdSeed++;
  220. var vertexSource;
  221. var fragmentSource;
  222. if (baseName.vertexElement) {
  223. vertexSource = document.getElementById(baseName.vertexElement);
  224. if (!vertexSource) {
  225. vertexSource = baseName.vertexElement;
  226. }
  227. }
  228. else {
  229. vertexSource = baseName.vertex || baseName;
  230. }
  231. if (baseName.fragmentElement) {
  232. fragmentSource = document.getElementById(baseName.fragmentElement);
  233. if (!fragmentSource) {
  234. fragmentSource = baseName.fragmentElement;
  235. }
  236. }
  237. else {
  238. fragmentSource = baseName.fragment || baseName;
  239. }
  240. var finalVertexCode;
  241. this._loadVertexShaderAsync(vertexSource)
  242. .then(function (vertexCode) {
  243. return _this._processIncludesAsync(vertexCode);
  244. })
  245. .then(function (vertexCodeWithIncludes) {
  246. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  247. return _this._loadFragmentShaderAsync(fragmentSource);
  248. })
  249. .then(function (fragmentCode) {
  250. return _this._processIncludesAsync(fragmentCode);
  251. })
  252. .then(function (fragmentCodeWithIncludes) {
  253. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  254. if (baseName) {
  255. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  256. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  257. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  258. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  259. }
  260. else {
  261. _this._vertexSourceCode = finalVertexCode;
  262. _this._fragmentSourceCode = migratedFragmentCode;
  263. }
  264. _this._prepareEffect();
  265. });
  266. }
  267. Object.defineProperty(Effect.prototype, "key", {
  268. /**
  269. * Unique key for this effect
  270. */
  271. get: function () {
  272. return this._key;
  273. },
  274. enumerable: true,
  275. configurable: true
  276. });
  277. /**
  278. * If the effect has been compiled and prepared.
  279. * @returns if the effect is compiled and prepared.
  280. */
  281. Effect.prototype.isReady = function () {
  282. return this._isReady;
  283. };
  284. /**
  285. * The engine the effect was initialized with.
  286. * @returns the engine.
  287. */
  288. Effect.prototype.getEngine = function () {
  289. return this._engine;
  290. };
  291. /**
  292. * The compiled webGL program for the effect
  293. * @returns the webGL program.
  294. */
  295. Effect.prototype.getProgram = function () {
  296. return this._program;
  297. };
  298. /**
  299. * The set of names of attribute variables for the shader.
  300. * @returns An array of attribute names.
  301. */
  302. Effect.prototype.getAttributesNames = function () {
  303. return this._attributesNames;
  304. };
  305. /**
  306. * Returns the attribute at the given index.
  307. * @param index The index of the attribute.
  308. * @returns The location of the attribute.
  309. */
  310. Effect.prototype.getAttributeLocation = function (index) {
  311. return this._attributes[index];
  312. };
  313. /**
  314. * Returns the attribute based on the name of the variable.
  315. * @param name of the attribute to look up.
  316. * @returns the attribute location.
  317. */
  318. Effect.prototype.getAttributeLocationByName = function (name) {
  319. var index = this._attributesNames.indexOf(name);
  320. return this._attributes[index];
  321. };
  322. /**
  323. * The number of attributes.
  324. * @returns the numnber of attributes.
  325. */
  326. Effect.prototype.getAttributesCount = function () {
  327. return this._attributes.length;
  328. };
  329. /**
  330. * Gets the index of a uniform variable.
  331. * @param uniformName of the uniform to look up.
  332. * @returns the index.
  333. */
  334. Effect.prototype.getUniformIndex = function (uniformName) {
  335. return this._uniformsNames.indexOf(uniformName);
  336. };
  337. /**
  338. * Returns the attribute based on the name of the variable.
  339. * @param uniformName of the uniform to look up.
  340. * @returns the location of the uniform.
  341. */
  342. Effect.prototype.getUniform = function (uniformName) {
  343. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  344. };
  345. /**
  346. * Returns an array of sampler variable names
  347. * @returns The array of sampler variable neames.
  348. */
  349. Effect.prototype.getSamplers = function () {
  350. return this._samplers;
  351. };
  352. /**
  353. * The error from the last compilation.
  354. * @returns the error string.
  355. */
  356. Effect.prototype.getCompilationError = function () {
  357. return this._compilationError;
  358. };
  359. /**
  360. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  361. * @param func The callback to be used.
  362. */
  363. Effect.prototype.executeWhenCompiled = function (func) {
  364. if (this.isReady()) {
  365. func(this);
  366. return;
  367. }
  368. this.onCompileObservable.add(function (effect) {
  369. func(effect);
  370. });
  371. };
  372. /** @ignore */
  373. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  374. if (BABYLON.Tools.IsWindowObjectExist()) {
  375. // DOM element ?
  376. if (vertex instanceof HTMLElement) {
  377. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  378. return Promise.resolve(vertexCode);
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. return Promise.resolve(vertexBinary);
  385. }
  386. // Is in local store ?
  387. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  388. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  389. }
  390. var vertexShaderUrl;
  391. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  392. vertexShaderUrl = vertex;
  393. }
  394. else {
  395. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  396. }
  397. // Vertex shader
  398. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  399. };
  400. /** @ignore */
  401. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  402. if (BABYLON.Tools.IsWindowObjectExist()) {
  403. // DOM element ?
  404. if (fragment instanceof HTMLElement) {
  405. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  406. return Promise.resolve(fragmentCode);
  407. }
  408. }
  409. // Base64 encoded ?
  410. if (fragment.substr(0, 7) === "base64:") {
  411. var fragmentBinary = window.atob(fragment.substr(7));
  412. return Promise.resolve(fragmentBinary);
  413. }
  414. // Is in local store ?
  415. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  416. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  417. }
  418. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  419. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  420. }
  421. var fragmentShaderUrl;
  422. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  423. fragmentShaderUrl = fragment;
  424. }
  425. else {
  426. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  427. }
  428. // Fragment shader
  429. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  430. };
  431. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  432. // Rebuild shaders source code
  433. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  434. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  435. vertexCode = prefix + vertexCode;
  436. fragmentCode = prefix + fragmentCode;
  437. // Number lines of shaders source code
  438. var i = 2;
  439. var regex = /\n/gm;
  440. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  441. i = 2;
  442. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  443. // Dump shaders name and formatted source code
  444. if (this.name.vertexElement) {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  447. }
  448. else if (this.name.vertex) {
  449. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  450. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  451. }
  452. else {
  453. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  454. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  455. }
  456. };
  457. ;
  458. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  459. var preparedSourceCode = this._processPrecision(sourceCode);
  460. if (this._engine.webGLVersion == 1) {
  461. return preparedSourceCode;
  462. }
  463. // Already converted
  464. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  465. return preparedSourceCode.replace("#version 300 es", "");
  466. }
  467. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  468. // Remove extensions
  469. // #extension GL_OES_standard_derivatives : enable
  470. // #extension GL_EXT_shader_texture_lod : enable
  471. // #extension GL_EXT_frag_depth : enable
  472. // #extension GL_EXT_draw_buffers : require
  473. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  474. var result = preparedSourceCode.replace(regex, "");
  475. // Migrate to GLSL v300
  476. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  477. result = result.replace(/attribute[ \t]/g, "in ");
  478. result = result.replace(/[ \t]attribute/g, " in");
  479. if (isFragment) {
  480. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  481. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  482. result = result.replace(/texture2D\s*\(/g, "texture(");
  483. result = result.replace(/textureCube\s*\(/g, "texture(");
  484. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  485. result = result.replace(/gl_FragColor/g, "glFragColor");
  486. result = result.replace(/gl_FragData/g, "glFragData");
  487. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  488. }
  489. return result;
  490. };
  491. Effect.prototype._processIncludesAsync = function (sourceCode) {
  492. var _this = this;
  493. return new Promise(function (resolve, reject) {
  494. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  495. var match = regex.exec(sourceCode);
  496. var returnValue = sourceCode;
  497. while (match != null) {
  498. var includeFile = match[1];
  499. // Uniform declaration
  500. if (includeFile.indexOf("__decl__") !== -1) {
  501. includeFile = includeFile.replace(/__decl__/, "");
  502. if (_this._engine.supportsUniformBuffers) {
  503. includeFile = includeFile.replace(/Vertex/, "Ubo");
  504. includeFile = includeFile.replace(/Fragment/, "Ubo");
  505. }
  506. includeFile = includeFile + "Declaration";
  507. }
  508. if (Effect.IncludesShadersStore[includeFile]) {
  509. // Substitution
  510. var includeContent = Effect.IncludesShadersStore[includeFile];
  511. if (match[2]) {
  512. var splits = match[3].split(",");
  513. for (var index = 0; index < splits.length; index += 2) {
  514. var source = new RegExp(splits[index], "g");
  515. var dest = splits[index + 1];
  516. includeContent = includeContent.replace(source, dest);
  517. }
  518. }
  519. if (match[4]) {
  520. var indexString = match[5];
  521. if (indexString.indexOf("..") !== -1) {
  522. var indexSplits = indexString.split("..");
  523. var minIndex = parseInt(indexSplits[0]);
  524. var maxIndex = parseInt(indexSplits[1]);
  525. var sourceIncludeContent = includeContent.slice(0);
  526. includeContent = "";
  527. if (isNaN(maxIndex)) {
  528. maxIndex = _this._indexParameters[indexSplits[1]];
  529. }
  530. for (var i = minIndex; i < maxIndex; i++) {
  531. if (!_this._engine.supportsUniformBuffers) {
  532. // Ubo replacement
  533. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  534. return p1 + "{X}";
  535. });
  536. }
  537. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  538. }
  539. }
  540. else {
  541. if (!_this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent = includeContent.replace(/\{X\}/g, indexString);
  548. }
  549. }
  550. // Replace
  551. returnValue = returnValue.replace(match[0], includeContent);
  552. }
  553. else {
  554. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  555. _this._engine._loadFileAsync(includeShaderUrl)
  556. .then(function (fileContent) {
  557. Effect.IncludesShadersStore[includeFile] = fileContent;
  558. return _this._processIncludesAsync(returnValue);
  559. })
  560. .then(function (returnValue) {
  561. resolve(returnValue);
  562. });
  563. return;
  564. }
  565. match = regex.exec(sourceCode);
  566. }
  567. resolve(returnValue);
  568. });
  569. };
  570. Effect.prototype._processPrecision = function (source) {
  571. if (source.indexOf("precision highp float") === -1) {
  572. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  573. source = "precision mediump float;\n" + source;
  574. }
  575. else {
  576. source = "precision highp float;\n" + source;
  577. }
  578. }
  579. else {
  580. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  581. source = source.replace("precision highp float", "precision mediump float");
  582. }
  583. }
  584. return source;
  585. };
  586. /**
  587. * Recompiles the webGL program
  588. * @param vertexSourceCode The source code for the vertex shader.
  589. * @param fragmentSourceCode The source code for the fragment shader.
  590. * @param onCompiled Callback called when completed.
  591. * @param onError Callback called on error.
  592. */
  593. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  594. var _this = this;
  595. this._isReady = false;
  596. this._vertexSourceCodeOverride = vertexSourceCode;
  597. this._fragmentSourceCodeOverride = fragmentSourceCode;
  598. this.onError = function (effect, error) {
  599. if (onError) {
  600. onError(error);
  601. }
  602. };
  603. this.onCompiled = function () {
  604. var scenes = _this.getEngine().scenes;
  605. for (var i = 0; i < scenes.length; i++) {
  606. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  607. }
  608. if (onCompiled) {
  609. onCompiled(_this._program);
  610. }
  611. };
  612. this._fallbacks = null;
  613. this._prepareEffect();
  614. };
  615. /**
  616. * Gets the uniform locations of the the specified variable names
  617. * @param names THe names of the variables to lookup.
  618. * @returns Array of locations in the same order as variable names.
  619. */
  620. Effect.prototype.getSpecificUniformLocations = function (names) {
  621. var engine = this._engine;
  622. return engine.getUniforms(this._program, names);
  623. };
  624. /**
  625. * Prepares the effect
  626. */
  627. Effect.prototype._prepareEffect = function () {
  628. var attributesNames = this._attributesNames;
  629. var defines = this.defines;
  630. var fallbacks = this._fallbacks;
  631. this._valueCache = {};
  632. var previousProgram = this._program;
  633. try {
  634. var engine = this._engine;
  635. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  636. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  637. }
  638. else {
  639. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  640. }
  641. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  642. if (engine.supportsUniformBuffers) {
  643. for (var name in this._uniformBuffersNames) {
  644. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  645. }
  646. }
  647. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  648. this._attributes = engine.getAttributes(this._program, attributesNames);
  649. var index;
  650. for (index = 0; index < this._samplers.length; index++) {
  651. var sampler = this.getUniform(this._samplers[index]);
  652. if (sampler == null) {
  653. this._samplers.splice(index, 1);
  654. index--;
  655. }
  656. }
  657. engine.bindSamplers(this);
  658. this._compilationError = "";
  659. this._isReady = true;
  660. if (this.onCompiled) {
  661. this.onCompiled(this);
  662. }
  663. this.onCompileObservable.notifyObservers(this);
  664. this.onCompileObservable.clear();
  665. // Unbind mesh reference in fallbacks
  666. if (this._fallbacks) {
  667. this._fallbacks.unBindMesh();
  668. }
  669. if (previousProgram) {
  670. this.getEngine()._deleteProgram(previousProgram);
  671. }
  672. }
  673. catch (e) {
  674. this._compilationError = e.message;
  675. // Let's go through fallbacks then
  676. BABYLON.Tools.Error("Unable to compile effect:");
  677. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  678. return " " + uniform;
  679. }));
  680. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  681. return " " + attribute;
  682. }));
  683. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  684. BABYLON.Tools.Error("Error: " + this._compilationError);
  685. if (previousProgram) {
  686. this._program = previousProgram;
  687. this._isReady = true;
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. }
  693. if (fallbacks && fallbacks.isMoreFallbacks) {
  694. BABYLON.Tools.Error("Trying next fallback.");
  695. this.defines = fallbacks.reduce(this.defines, this);
  696. this._prepareEffect();
  697. }
  698. else {
  699. if (this.onError) {
  700. this.onError(this, this._compilationError);
  701. }
  702. this.onErrorObservable.notifyObservers(this);
  703. this.onErrorObservable.clear();
  704. // Unbind mesh reference in fallbacks
  705. if (this._fallbacks) {
  706. this._fallbacks.unBindMesh();
  707. }
  708. }
  709. }
  710. };
  711. Object.defineProperty(Effect.prototype, "isSupported", {
  712. /**
  713. * Checks if the effect is supported. (Must be called after compilation)
  714. */
  715. get: function () {
  716. return this._compilationError === "";
  717. },
  718. enumerable: true,
  719. configurable: true
  720. });
  721. /**
  722. * Binds a texture to the engine to be used as output of the shader.
  723. * @param channel Name of the output variable.
  724. * @param texture Texture to bind.
  725. */
  726. Effect.prototype._bindTexture = function (channel, texture) {
  727. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  728. };
  729. /**
  730. * Sets a texture on the engine to be used in the shader.
  731. * @param channel Name of the sampler variable.
  732. * @param texture Texture to set.
  733. */
  734. Effect.prototype.setTexture = function (channel, texture) {
  735. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  736. };
  737. /**
  738. * Sets an array of textures on the engine to be used in the shader.
  739. * @param channel Name of the variable.
  740. * @param textures Textures to set.
  741. */
  742. Effect.prototype.setTextureArray = function (channel, textures) {
  743. if (this._samplers.indexOf(channel + "Ex") === -1) {
  744. var initialPos = this._samplers.indexOf(channel);
  745. for (var index = 1; index < textures.length; index++) {
  746. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  747. }
  748. }
  749. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  750. };
  751. /**
  752. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  753. * @param channel Name of the sampler variable.
  754. * @param postProcess Post process to get the input texture from.
  755. */
  756. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  757. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  758. };
  759. /** @ignore */
  760. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  761. var cache = this._valueCache[uniformName];
  762. var flag = matrix.updateFlag;
  763. if (cache !== undefined && cache === flag) {
  764. return false;
  765. }
  766. this._valueCache[uniformName] = flag;
  767. return true;
  768. };
  769. /** @ignore */
  770. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  771. var cache = this._valueCache[uniformName];
  772. if (!cache) {
  773. cache = [x, y];
  774. this._valueCache[uniformName] = cache;
  775. return true;
  776. }
  777. var changed = false;
  778. if (cache[0] !== x) {
  779. cache[0] = x;
  780. changed = true;
  781. }
  782. if (cache[1] !== y) {
  783. cache[1] = y;
  784. changed = true;
  785. }
  786. return changed;
  787. };
  788. /** @ignore */
  789. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y, z];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. if (cache[2] !== z) {
  806. cache[2] = z;
  807. changed = true;
  808. }
  809. return changed;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y, z, w];
  816. this._valueCache[uniformName] = cache;
  817. return true;
  818. }
  819. var changed = false;
  820. if (cache[0] !== x) {
  821. cache[0] = x;
  822. changed = true;
  823. }
  824. if (cache[1] !== y) {
  825. cache[1] = y;
  826. changed = true;
  827. }
  828. if (cache[2] !== z) {
  829. cache[2] = z;
  830. changed = true;
  831. }
  832. if (cache[3] !== w) {
  833. cache[3] = w;
  834. changed = true;
  835. }
  836. return changed;
  837. };
  838. /**
  839. * Binds a buffer to a uniform.
  840. * @param buffer Buffer to bind.
  841. * @param name Name of the uniform variable to bind to.
  842. */
  843. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  844. var bufferName = this._uniformBuffersNames[name];
  845. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  846. return;
  847. }
  848. Effect._baseCache[bufferName] = buffer;
  849. this._engine.bindUniformBufferBase(buffer, bufferName);
  850. };
  851. /**
  852. * Binds block to a uniform.
  853. * @param blockName Name of the block to bind.
  854. * @param index Index to bind.
  855. */
  856. Effect.prototype.bindUniformBlock = function (blockName, index) {
  857. this._engine.bindUniformBlock(this._program, blockName, index);
  858. };
  859. /**
  860. * Sets an interger value on a uniform variable.
  861. * @param uniformName Name of the variable.
  862. * @param value Value to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setInt = function (uniformName, value) {
  866. var cache = this._valueCache[uniformName];
  867. if (cache !== undefined && cache === value)
  868. return this;
  869. this._valueCache[uniformName] = value;
  870. this._engine.setInt(this.getUniform(uniformName), value);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array on a uniform variable.
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray2 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray2(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray3 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray3(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray4 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray4(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array on a uniform variable.
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray2 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray2(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray3 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray3(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray4 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray4(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets matrices on a uniform variable.
  1007. * @param uniformName Name of the variable.
  1008. * @param matrices matrices to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1012. if (!matrices) {
  1013. return this;
  1014. }
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1017. return this;
  1018. };
  1019. /**
  1020. * Sets matrix on a uniform variable.
  1021. * @param uniformName Name of the variable.
  1022. * @param matrix matrix to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1026. if (this._cacheMatrix(uniformName, matrix)) {
  1027. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1028. }
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1044. * @param uniformName Name of the variable.
  1045. * @param matrix matrix to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a float on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param value value to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat = function (uniformName, value) {
  1060. var cache = this._valueCache[uniformName];
  1061. if (cache !== undefined && cache === value)
  1062. return this;
  1063. this._valueCache[uniformName] = value;
  1064. this._engine.setFloat(this.getUniform(uniformName), value);
  1065. return this;
  1066. };
  1067. /**
  1068. * Sets a boolean on a uniform variable.
  1069. * @param uniformName Name of the variable.
  1070. * @param bool value to be set.
  1071. * @returns this effect.
  1072. */
  1073. Effect.prototype.setBool = function (uniformName, bool) {
  1074. var cache = this._valueCache[uniformName];
  1075. if (cache !== undefined && cache === bool)
  1076. return this;
  1077. this._valueCache[uniformName] = bool;
  1078. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector2 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector2 vector2 to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1088. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1089. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float2 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float2.
  1097. * @param y Second float in float2.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1101. if (this._cacheFloat2(uniformName, x, y)) {
  1102. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1103. }
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets a Vector3 on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param vector3 Value to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1113. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1114. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a float3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param x First float in float3.
  1122. * @param y Second float in float3.
  1123. * @param z Third float in float3.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1127. if (this._cacheFloat3(uniformName, x, y, z)) {
  1128. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a Vector4 on a uniform variable.
  1134. * @param uniformName Name of the variable.
  1135. * @param vector4 Value to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1139. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1140. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1141. }
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a float4 on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param x First float in float4.
  1148. * @param y Second float in float4.
  1149. * @param z Third float in float4.
  1150. * @param w Fourth float in float4.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1154. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1155. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color3 on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param color3 Value to be set.
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setColor3 = function (uniformName, color3) {
  1166. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1167. this._engine.setColor3(this.getUniform(uniformName), color3);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a Color4 on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param color3 Value to be set.
  1175. * @param alpha Alpha value to be set.
  1176. * @returns this effect.
  1177. */
  1178. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1179. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1180. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1181. }
  1182. return this;
  1183. };
  1184. /**
  1185. * Sets a Color4 on a uniform variable
  1186. * @param uniformName defines the name of the variable
  1187. * @param color4 defines the value to be set
  1188. * @returns this effect.
  1189. */
  1190. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1191. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1192. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1193. }
  1194. return this;
  1195. };
  1196. /**
  1197. * Resets the cache of effects.
  1198. */
  1199. Effect.ResetCache = function () {
  1200. Effect._baseCache = {};
  1201. };
  1202. Effect._uniqueIdSeed = 0;
  1203. Effect._baseCache = {};
  1204. // Statics
  1205. /**
  1206. * Store of each shader (The can be looked up using effect.key)
  1207. */
  1208. Effect.ShadersStore = {};
  1209. /**
  1210. * Store of each included file for a shader (The can be looked up using effect.key)
  1211. */
  1212. Effect.IncludesShadersStore = {};
  1213. return Effect;
  1214. }());
  1215. BABYLON.Effect = Effect;
  1216. })(BABYLON || (BABYLON = {}));
  1217. //# sourceMappingURL=babylon.effect.js.map
  1218. //# sourceMappingURL=babylon.types.js.map
  1219. var BABYLON;
  1220. (function (BABYLON) {
  1221. var KeyboardEventTypes = /** @class */ (function () {
  1222. function KeyboardEventTypes() {
  1223. }
  1224. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1225. get: function () {
  1226. return KeyboardEventTypes._KEYDOWN;
  1227. },
  1228. enumerable: true,
  1229. configurable: true
  1230. });
  1231. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1232. get: function () {
  1233. return KeyboardEventTypes._KEYUP;
  1234. },
  1235. enumerable: true,
  1236. configurable: true
  1237. });
  1238. KeyboardEventTypes._KEYDOWN = 0x01;
  1239. KeyboardEventTypes._KEYUP = 0x02;
  1240. return KeyboardEventTypes;
  1241. }());
  1242. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1243. var KeyboardInfo = /** @class */ (function () {
  1244. function KeyboardInfo(type, event) {
  1245. this.type = type;
  1246. this.event = event;
  1247. }
  1248. return KeyboardInfo;
  1249. }());
  1250. BABYLON.KeyboardInfo = KeyboardInfo;
  1251. /**
  1252. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1253. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1254. */
  1255. var KeyboardInfoPre = /** @class */ (function (_super) {
  1256. __extends(KeyboardInfoPre, _super);
  1257. function KeyboardInfoPre(type, event) {
  1258. var _this = _super.call(this, type, event) || this;
  1259. _this.skipOnPointerObservable = false;
  1260. return _this;
  1261. }
  1262. return KeyboardInfoPre;
  1263. }(KeyboardInfo));
  1264. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1265. })(BABYLON || (BABYLON = {}));
  1266. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1267. var BABYLON;
  1268. (function (BABYLON) {
  1269. var PointerEventTypes = /** @class */ (function () {
  1270. function PointerEventTypes() {
  1271. }
  1272. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1273. get: function () {
  1274. return PointerEventTypes._POINTERDOWN;
  1275. },
  1276. enumerable: true,
  1277. configurable: true
  1278. });
  1279. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1280. get: function () {
  1281. return PointerEventTypes._POINTERUP;
  1282. },
  1283. enumerable: true,
  1284. configurable: true
  1285. });
  1286. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1287. get: function () {
  1288. return PointerEventTypes._POINTERMOVE;
  1289. },
  1290. enumerable: true,
  1291. configurable: true
  1292. });
  1293. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERWHEEL;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERPICK;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERTAP;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERDOUBLETAP;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. PointerEventTypes._POINTERDOWN = 0x01;
  1322. PointerEventTypes._POINTERUP = 0x02;
  1323. PointerEventTypes._POINTERMOVE = 0x04;
  1324. PointerEventTypes._POINTERWHEEL = 0x08;
  1325. PointerEventTypes._POINTERPICK = 0x10;
  1326. PointerEventTypes._POINTERTAP = 0x20;
  1327. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1328. return PointerEventTypes;
  1329. }());
  1330. BABYLON.PointerEventTypes = PointerEventTypes;
  1331. var PointerInfoBase = /** @class */ (function () {
  1332. function PointerInfoBase(type, event) {
  1333. this.type = type;
  1334. this.event = event;
  1335. }
  1336. return PointerInfoBase;
  1337. }());
  1338. BABYLON.PointerInfoBase = PointerInfoBase;
  1339. /**
  1340. * This class is used to store pointer related info for the onPrePointerObservable event.
  1341. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1342. */
  1343. var PointerInfoPre = /** @class */ (function (_super) {
  1344. __extends(PointerInfoPre, _super);
  1345. function PointerInfoPre(type, event, localX, localY) {
  1346. var _this = _super.call(this, type, event) || this;
  1347. _this.skipOnPointerObservable = false;
  1348. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1349. return _this;
  1350. }
  1351. return PointerInfoPre;
  1352. }(PointerInfoBase));
  1353. BABYLON.PointerInfoPre = PointerInfoPre;
  1354. /**
  1355. * This type contains all the data related to a pointer event in Babylon.js.
  1356. * 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.
  1357. */
  1358. var PointerInfo = /** @class */ (function (_super) {
  1359. __extends(PointerInfo, _super);
  1360. function PointerInfo(type, event, pickInfo) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.pickInfo = pickInfo;
  1363. return _this;
  1364. }
  1365. return PointerInfo;
  1366. }(PointerInfoBase));
  1367. BABYLON.PointerInfo = PointerInfo;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.pointerEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. BABYLON.ToGammaSpace = 1 / 2.2;
  1373. BABYLON.ToLinearSpace = 2.2;
  1374. BABYLON.Epsilon = 0.001;
  1375. /**
  1376. * Class used to hold a RBG color
  1377. */
  1378. var Color3 = /** @class */ (function () {
  1379. /**
  1380. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1381. * @param r defines the red component (between 0 and 1, default is 0)
  1382. * @param g defines the green component (between 0 and 1, default is 0)
  1383. * @param b defines the blue component (between 0 and 1, default is 0)
  1384. */
  1385. function Color3(
  1386. /**
  1387. * Defines the red component (between 0 and 1, default is 0)
  1388. */
  1389. r,
  1390. /**
  1391. * Defines the green component (between 0 and 1, default is 0)
  1392. */
  1393. g,
  1394. /**
  1395. * Defines the blue component (between 0 and 1, default is 0)
  1396. */
  1397. b) {
  1398. if (r === void 0) { r = 0; }
  1399. if (g === void 0) { g = 0; }
  1400. if (b === void 0) { b = 0; }
  1401. this.r = r;
  1402. this.g = g;
  1403. this.b = b;
  1404. }
  1405. /**
  1406. * Creates a string with the Color3 current values
  1407. * @returns the string representation of the Color3 object
  1408. */
  1409. Color3.prototype.toString = function () {
  1410. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1411. };
  1412. /**
  1413. * Returns the string "Color3"
  1414. * @returns "Color3"
  1415. */
  1416. Color3.prototype.getClassName = function () {
  1417. return "Color3";
  1418. };
  1419. /**
  1420. * Compute the Color3 hash code
  1421. * @returns an unique number that can be used to hash Color3 objects
  1422. */
  1423. Color3.prototype.getHashCode = function () {
  1424. var hash = this.r || 0;
  1425. hash = (hash * 397) ^ (this.g || 0);
  1426. hash = (hash * 397) ^ (this.b || 0);
  1427. return hash;
  1428. };
  1429. // Operators
  1430. /**
  1431. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1432. * @param array defines the array where to store the r,g,b components
  1433. * @param index defines an optional index in the target array to define where to start storing values
  1434. * @returns the current Color3 object
  1435. */
  1436. Color3.prototype.toArray = function (array, index) {
  1437. if (index === undefined) {
  1438. index = 0;
  1439. }
  1440. array[index] = this.r;
  1441. array[index + 1] = this.g;
  1442. array[index + 2] = this.b;
  1443. return this;
  1444. };
  1445. /**
  1446. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1447. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1448. * @returns a new {BABYLON.Color4} object
  1449. */
  1450. Color3.prototype.toColor4 = function (alpha) {
  1451. if (alpha === void 0) { alpha = 1; }
  1452. return new Color4(this.r, this.g, this.b, alpha);
  1453. };
  1454. /**
  1455. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1456. * @returns the new array
  1457. */
  1458. Color3.prototype.asArray = function () {
  1459. var result = new Array();
  1460. this.toArray(result, 0);
  1461. return result;
  1462. };
  1463. /**
  1464. * Returns the luminance value
  1465. * @returns a float value
  1466. */
  1467. Color3.prototype.toLuminance = function () {
  1468. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1469. };
  1470. /**
  1471. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1472. * @param otherColor defines the second operand
  1473. * @returns the new Color3 object
  1474. */
  1475. Color3.prototype.multiply = function (otherColor) {
  1476. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1477. };
  1478. /**
  1479. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1480. * @param otherColor defines the second operand
  1481. * @param result defines the Color3 object where to store the result
  1482. * @returns the current Color3
  1483. */
  1484. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1485. result.r = this.r * otherColor.r;
  1486. result.g = this.g * otherColor.g;
  1487. result.b = this.b * otherColor.b;
  1488. return this;
  1489. };
  1490. /**
  1491. * Determines equality between Color3 objects
  1492. * @param otherColor defines the second operand
  1493. * @returns true if the rgb values are equal to the passed ones
  1494. */
  1495. Color3.prototype.equals = function (otherColor) {
  1496. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1497. };
  1498. /**
  1499. * Determines equality between the current Color3 object and a set of r,b,g values
  1500. * @param r defines the red component to check
  1501. * @param g defines the green component to check
  1502. * @param b defines the blue component to check
  1503. * @returns true if the rgb values are equal to the passed ones
  1504. */
  1505. Color3.prototype.equalsFloats = function (r, g, b) {
  1506. return this.r === r && this.g === g && this.b === b;
  1507. };
  1508. /**
  1509. * Multiplies in place each rgb value by scale
  1510. * @param scale defines the scaling factor
  1511. * @returns the updated Color3.
  1512. */
  1513. Color3.prototype.scale = function (scale) {
  1514. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1515. };
  1516. /**
  1517. * Multiplies the rgb values by scale and stores the result into "result"
  1518. * @param scale defines the scaling factor
  1519. * @param result defines the Color3 object where to store the result
  1520. * @returns the unmodified current Color3.
  1521. */
  1522. Color3.prototype.scaleToRef = function (scale, result) {
  1523. result.r = this.r * scale;
  1524. result.g = this.g * scale;
  1525. result.b = this.b * scale;
  1526. return this;
  1527. };
  1528. /**
  1529. * Clamps the rgb values by the min and max values and stores the result into "result"
  1530. * @param min defines minimum clamping value (default is 0)
  1531. * @param max defines maximum clamping value (default is 1)
  1532. * @param result defines color to store the result into
  1533. * @returns the original Color3
  1534. */
  1535. Color3.prototype.clampToRef = function (min, max, result) {
  1536. if (min === void 0) { min = 0; }
  1537. if (max === void 0) { max = 1; }
  1538. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1539. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1540. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1545. * @param otherColor defines the second operand
  1546. * @returns the new Color3
  1547. */
  1548. Color3.prototype.add = function (otherColor) {
  1549. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1550. };
  1551. /**
  1552. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1553. * @param otherColor defines the second operand
  1554. * @param result defines Color3 object to store the result into
  1555. * @returns the unmodified current Color3
  1556. */
  1557. Color3.prototype.addToRef = function (otherColor, result) {
  1558. result.r = this.r + otherColor.r;
  1559. result.g = this.g + otherColor.g;
  1560. result.b = this.b + otherColor.b;
  1561. return this;
  1562. };
  1563. /**
  1564. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1565. * @param otherColor defines the second operand
  1566. * @returns the new Color3
  1567. */
  1568. Color3.prototype.subtract = function (otherColor) {
  1569. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1570. };
  1571. /**
  1572. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1573. * @param otherColor defines the second operand
  1574. * @param result defines Color3 object to store the result into
  1575. * @returns the unmodified current Color3
  1576. */
  1577. Color3.prototype.subtractToRef = function (otherColor, result) {
  1578. result.r = this.r - otherColor.r;
  1579. result.g = this.g - otherColor.g;
  1580. result.b = this.b - otherColor.b;
  1581. return this;
  1582. };
  1583. /**
  1584. * Copy the current object
  1585. * @returns a new Color3 copied the current one
  1586. */
  1587. Color3.prototype.clone = function () {
  1588. return new Color3(this.r, this.g, this.b);
  1589. };
  1590. /**
  1591. * Copies the rgb values from the source in the current Color3
  1592. * @param source defines the source Color3 object
  1593. * @returns the updated Color3 object
  1594. */
  1595. Color3.prototype.copyFrom = function (source) {
  1596. this.r = source.r;
  1597. this.g = source.g;
  1598. this.b = source.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Updates the Color3 rgb values from the passed floats
  1603. * @param r defines the red component to read from
  1604. * @param g defines the green component to read from
  1605. * @param b defines the blue component to read from
  1606. * @returns the current Color3 object
  1607. */
  1608. Color3.prototype.copyFromFloats = function (r, g, b) {
  1609. this.r = r;
  1610. this.g = g;
  1611. this.b = b;
  1612. return this;
  1613. };
  1614. /**
  1615. * Updates the Color3 rgb values from the passed floats
  1616. * @param r defines the red component to read from
  1617. * @param g defines the green component to read from
  1618. * @param b defines the blue component to read from
  1619. * @returns the current Color3 object
  1620. */
  1621. Color3.prototype.set = function (r, g, b) {
  1622. return this.copyFromFloats(r, g, b);
  1623. };
  1624. /**
  1625. * Compute the Color3 hexadecimal code as a string
  1626. * @returns a string containing the hexadecimal representation of the Color3 object
  1627. */
  1628. Color3.prototype.toHexString = function () {
  1629. var intR = (this.r * 255) | 0;
  1630. var intG = (this.g * 255) | 0;
  1631. var intB = (this.b * 255) | 0;
  1632. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1633. };
  1634. /**
  1635. * Computes a new Color3 converted from the current one to linear space
  1636. * @returns a new Color3 object
  1637. */
  1638. Color3.prototype.toLinearSpace = function () {
  1639. var convertedColor = new Color3();
  1640. this.toLinearSpaceToRef(convertedColor);
  1641. return convertedColor;
  1642. };
  1643. /**
  1644. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1645. * @param convertedColor defines the Color3 object where to store the linear space version
  1646. * @returns the unmodified Color3
  1647. */
  1648. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1649. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1650. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1651. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1652. return this;
  1653. };
  1654. /**
  1655. * Computes a new Color3 converted from the current one to gamma space
  1656. * @returns a new Color3 object
  1657. */
  1658. Color3.prototype.toGammaSpace = function () {
  1659. var convertedColor = new Color3();
  1660. this.toGammaSpaceToRef(convertedColor);
  1661. return convertedColor;
  1662. };
  1663. /**
  1664. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1665. * @param convertedColor defines the Color3 object where to store the gamma space version
  1666. * @returns the unmodified Color3
  1667. */
  1668. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1669. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1670. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1671. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1672. return this;
  1673. };
  1674. // Statics
  1675. /**
  1676. * Creates a new Color3 from the string containing valid hexadecimal values
  1677. * @param hex defines a string containing valid hexadecimal values
  1678. * @returns a new Color3 object
  1679. */
  1680. Color3.FromHexString = function (hex) {
  1681. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1682. return new Color3(0, 0, 0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. return Color3.FromInts(r, g, b);
  1688. };
  1689. /**
  1690. * Creates a new Vector3 from the starting index of the passed array
  1691. * @param array defines the source array
  1692. * @param offset defines an offset in the source array
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.FromArray = function (array, offset) {
  1696. if (offset === void 0) { offset = 0; }
  1697. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1698. };
  1699. /**
  1700. * Creates a new Color3 from integer values (< 256)
  1701. * @param r defines the red component to read from (value between 0 and 255)
  1702. * @param g defines the green component to read from (value between 0 and 255)
  1703. * @param b defines the blue component to read from (value between 0 and 255)
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.FromInts = function (r, g, b) {
  1707. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1708. };
  1709. /**
  1710. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1711. * @param start defines the start Color3 value
  1712. * @param end defines the end Color3 value
  1713. * @param amount defines the gradient value between start and end
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Lerp = function (start, end, amount) {
  1717. var r = start.r + ((end.r - start.r) * amount);
  1718. var g = start.g + ((end.g - start.g) * amount);
  1719. var b = start.b + ((end.b - start.b) * amount);
  1720. return new Color3(r, g, b);
  1721. };
  1722. /**
  1723. * Returns a Color3 value containing a red color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Red = function () { return new Color3(1, 0, 0); };
  1727. /**
  1728. * Returns a Color3 value containing a green color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Green = function () { return new Color3(0, 1, 0); };
  1732. /**
  1733. * Returns a Color3 value containing a blue color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1737. /**
  1738. * Returns a Color3 value containing a black color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Black = function () { return new Color3(0, 0, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a white color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.White = function () { return new Color3(1, 1, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a purple color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1752. /**
  1753. * Returns a Color3 value containing a magenta color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a yellow color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a gray color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1767. /**
  1768. * Returns a Color3 value containing a teal color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1772. /**
  1773. * Returns a Color3 value containing a random color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1777. return Color3;
  1778. }());
  1779. BABYLON.Color3 = Color3;
  1780. /**
  1781. * Class used to hold a RBGA color
  1782. */
  1783. var Color4 = /** @class */ (function () {
  1784. /**
  1785. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1786. * @param r defines the red component (between 0 and 1, default is 0)
  1787. * @param g defines the green component (between 0 and 1, default is 0)
  1788. * @param b defines the blue component (between 0 and 1, default is 0)
  1789. * @param a defines the alpha component (between 0 and 1, default is 1)
  1790. */
  1791. function Color4(
  1792. /**
  1793. * Defines the red component (between 0 and 1, default is 0)
  1794. */
  1795. r,
  1796. /**
  1797. * Defines the green component (between 0 and 1, default is 0)
  1798. */
  1799. g,
  1800. /**
  1801. * Defines the blue component (between 0 and 1, default is 0)
  1802. */
  1803. b,
  1804. /**
  1805. * Defines the alpha component (between 0 and 1, default is 1)
  1806. */
  1807. a) {
  1808. if (r === void 0) { r = 0; }
  1809. if (g === void 0) { g = 0; }
  1810. if (b === void 0) { b = 0; }
  1811. if (a === void 0) { a = 1; }
  1812. this.r = r;
  1813. this.g = g;
  1814. this.b = b;
  1815. this.a = a;
  1816. }
  1817. // Operators
  1818. /**
  1819. * Adds in place the passed Color4 values to the current Color4 object
  1820. * @param right defines the second operand
  1821. * @returns the current updated Color4 object
  1822. */
  1823. Color4.prototype.addInPlace = function (right) {
  1824. this.r += right.r;
  1825. this.g += right.g;
  1826. this.b += right.b;
  1827. this.a += right.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1832. * @returns the new array
  1833. */
  1834. Color4.prototype.asArray = function () {
  1835. var result = new Array();
  1836. this.toArray(result, 0);
  1837. return result;
  1838. };
  1839. /**
  1840. * Stores from the starting index in the passed array the Color4 successive values
  1841. * @param array defines the array where to store the r,g,b components
  1842. * @param index defines an optional index in the target array to define where to start storing values
  1843. * @returns the current Color4 object
  1844. */
  1845. Color4.prototype.toArray = function (array, index) {
  1846. if (index === undefined) {
  1847. index = 0;
  1848. }
  1849. array[index] = this.r;
  1850. array[index + 1] = this.g;
  1851. array[index + 2] = this.b;
  1852. array[index + 3] = this.a;
  1853. return this;
  1854. };
  1855. /**
  1856. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1857. * @param right defines the second operand
  1858. * @returns a new Color4 object
  1859. */
  1860. Color4.prototype.add = function (right) {
  1861. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.subtract = function (right) {
  1869. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1870. };
  1871. /**
  1872. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1873. * @param right defines the second operand
  1874. * @param result defines the Color4 object where to store the result
  1875. * @returns the current Color4 object
  1876. */
  1877. Color4.prototype.subtractToRef = function (right, result) {
  1878. result.r = this.r - right.r;
  1879. result.g = this.g - right.g;
  1880. result.b = this.b - right.b;
  1881. result.a = this.a - right.a;
  1882. return this;
  1883. };
  1884. /**
  1885. * Creates a new Color4 with the current Color4 values multiplied by scale
  1886. * @param scale defines the scaling factor to apply
  1887. * @returns a new Color4 object
  1888. */
  1889. Color4.prototype.scale = function (scale) {
  1890. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1891. };
  1892. /**
  1893. * Multiplies the current Color4 values by scale and stores the result in "result"
  1894. * @param scale defines the scaling factor to apply
  1895. * @param result defines the Color4 object where to store the result
  1896. * @returns the current Color4.
  1897. */
  1898. Color4.prototype.scaleToRef = function (scale, result) {
  1899. result.r = this.r * scale;
  1900. result.g = this.g * scale;
  1901. result.b = this.b * scale;
  1902. result.a = this.a * scale;
  1903. return this;
  1904. };
  1905. /**
  1906. * Clamps the rgb values by the min and max values and stores the result into "result"
  1907. * @param min defines minimum clamping value (default is 0)
  1908. * @param max defines maximum clamping value (default is 1)
  1909. * @param result defines color to store the result into.
  1910. * @returns the cuurent Color4
  1911. */
  1912. Color4.prototype.clampToRef = function (min, max, result) {
  1913. if (min === void 0) { min = 0; }
  1914. if (max === void 0) { max = 1; }
  1915. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1916. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1917. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1918. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1919. return this;
  1920. };
  1921. /**
  1922. * Multipy an Color4 value by another and return a new Color4 object
  1923. * @param color defines the Color4 value to multiply by
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.multiply = function (color) {
  1927. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1928. };
  1929. /**
  1930. * Multipy a Color4 value by another and push the result in a reference value
  1931. * @param color defines the Color4 value to multiply by
  1932. * @param result defines the Color4 to fill the result in
  1933. * @returns the result Color4
  1934. */
  1935. Color4.prototype.multiplyToRef = function (color, result) {
  1936. result.r = this.r * color.r;
  1937. result.g = this.g * color.g;
  1938. result.b = this.b * color.b;
  1939. result.a = this.a * color.a;
  1940. return result;
  1941. };
  1942. /**
  1943. * Creates a string with the Color4 current values
  1944. * @returns the string representation of the Color4 object
  1945. */
  1946. Color4.prototype.toString = function () {
  1947. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1948. };
  1949. /**
  1950. * Returns the string "Color4"
  1951. * @returns "Color4"
  1952. */
  1953. Color4.prototype.getClassName = function () {
  1954. return "Color4";
  1955. };
  1956. /**
  1957. * Compute the Color4 hash code
  1958. * @returns an unique number that can be used to hash Color4 objects
  1959. */
  1960. Color4.prototype.getHashCode = function () {
  1961. var hash = this.r || 0;
  1962. hash = (hash * 397) ^ (this.g || 0);
  1963. hash = (hash * 397) ^ (this.b || 0);
  1964. hash = (hash * 397) ^ (this.a || 0);
  1965. return hash;
  1966. };
  1967. /**
  1968. * Creates a new Color4 copied from the current one
  1969. * @returns a new Color4 object
  1970. */
  1971. Color4.prototype.clone = function () {
  1972. return new Color4(this.r, this.g, this.b, this.a);
  1973. };
  1974. /**
  1975. * Copies the passed Color4 values into the current one
  1976. * @param source defines the source Color4 object
  1977. * @returns the current updated Color4 object
  1978. */
  1979. Color4.prototype.copyFrom = function (source) {
  1980. this.r = source.r;
  1981. this.g = source.g;
  1982. this.b = source.b;
  1983. this.a = source.a;
  1984. return this;
  1985. };
  1986. /**
  1987. * Copies the passed float values into the current one
  1988. * @param r defines the red component to read from
  1989. * @param g defines the green component to read from
  1990. * @param b defines the blue component to read from
  1991. * @param a defines the alpha component to read from
  1992. * @returns the current updated Color4 object
  1993. */
  1994. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1995. this.r = r;
  1996. this.g = g;
  1997. this.b = b;
  1998. this.a = a;
  1999. return this;
  2000. };
  2001. /**
  2002. * Copies the passed float values into the current one
  2003. * @param r defines the red component to read from
  2004. * @param g defines the green component to read from
  2005. * @param b defines the blue component to read from
  2006. * @param a defines the alpha component to read from
  2007. * @returns the current updated Color4 object
  2008. */
  2009. Color4.prototype.set = function (r, g, b, a) {
  2010. return this.copyFromFloats(r, g, b, a);
  2011. };
  2012. /**
  2013. * Compute the Color4 hexadecimal code as a string
  2014. * @returns a string containing the hexadecimal representation of the Color4 object
  2015. */
  2016. Color4.prototype.toHexString = function () {
  2017. var intR = (this.r * 255) | 0;
  2018. var intG = (this.g * 255) | 0;
  2019. var intB = (this.b * 255) | 0;
  2020. var intA = (this.a * 255) | 0;
  2021. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2022. };
  2023. /**
  2024. * Computes a new Color4 converted from the current one to linear space
  2025. * @returns a new Color4 object
  2026. */
  2027. Color4.prototype.toLinearSpace = function () {
  2028. var convertedColor = new Color4();
  2029. this.toLinearSpaceToRef(convertedColor);
  2030. return convertedColor;
  2031. };
  2032. /**
  2033. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2034. * @param convertedColor defines the Color4 object where to store the linear space version
  2035. * @returns the unmodified Color4
  2036. */
  2037. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2038. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2039. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2040. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2041. convertedColor.a = this.a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to gamma space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toGammaSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toGammaSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the gamma space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. // Statics
  2066. /**
  2067. * Creates a new Color4 from the string containing valid hexadecimal values
  2068. * @param hex defines a string containing valid hexadecimal values
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.FromHexString = function (hex) {
  2072. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2073. return new Color4(0.0, 0.0, 0.0, 0.0);
  2074. }
  2075. var r = parseInt(hex.substring(1, 3), 16);
  2076. var g = parseInt(hex.substring(3, 5), 16);
  2077. var b = parseInt(hex.substring(5, 7), 16);
  2078. var a = parseInt(hex.substring(7, 9), 16);
  2079. return Color4.FromInts(r, g, b, a);
  2080. };
  2081. /**
  2082. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2083. * @param left defines the start value
  2084. * @param right defines the end value
  2085. * @param amount defines the gradient factor
  2086. * @returns a new Color4 object
  2087. */
  2088. Color4.Lerp = function (left, right, amount) {
  2089. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2090. Color4.LerpToRef(left, right, amount, result);
  2091. return result;
  2092. };
  2093. /**
  2094. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2095. * @param left defines the start value
  2096. * @param right defines the end value
  2097. * @param amount defines the gradient factor
  2098. * @param result defines the Color4 object where to store data
  2099. */
  2100. Color4.LerpToRef = function (left, right, amount, result) {
  2101. result.r = left.r + (right.r - left.r) * amount;
  2102. result.g = left.g + (right.g - left.g) * amount;
  2103. result.b = left.b + (right.b - left.b) * amount;
  2104. result.a = left.a + (right.a - left.a) * amount;
  2105. };
  2106. /**
  2107. * Creates a new Color4 from the starting index element of the passed array
  2108. * @param array defines the source array to read from
  2109. * @param offset defines the offset in the source array
  2110. * @returns a new Color4 object
  2111. */
  2112. Color4.FromArray = function (array, offset) {
  2113. if (offset === void 0) { offset = 0; }
  2114. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2115. };
  2116. /**
  2117. * Creates a new Color3 from integer values (< 256)
  2118. * @param r defines the red component to read from (value between 0 and 255)
  2119. * @param g defines the green component to read from (value between 0 and 255)
  2120. * @param b defines the blue component to read from (value between 0 and 255)
  2121. * @param a defines the alpha component to read from (value between 0 and 255)
  2122. * @returns a new Color3 object
  2123. */
  2124. Color4.FromInts = function (r, g, b, a) {
  2125. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2126. };
  2127. /**
  2128. * Check the content of a given array and convert it to an array containing RGBA data
  2129. * If the original array was already containing count * 4 values then it is returned directly
  2130. * @param colors defines the array to check
  2131. * @param count defines the number of RGBA data to expect
  2132. * @returns an array containing count * 4 values (RGBA)
  2133. */
  2134. Color4.CheckColors4 = function (colors, count) {
  2135. // Check if color3 was used
  2136. if (colors.length === count * 3) {
  2137. var colors4 = [];
  2138. for (var index = 0; index < colors.length; index += 3) {
  2139. var newIndex = (index / 3) * 4;
  2140. colors4[newIndex] = colors[index];
  2141. colors4[newIndex + 1] = colors[index + 1];
  2142. colors4[newIndex + 2] = colors[index + 2];
  2143. colors4[newIndex + 3] = 1.0;
  2144. }
  2145. return colors4;
  2146. }
  2147. return colors;
  2148. };
  2149. return Color4;
  2150. }());
  2151. BABYLON.Color4 = Color4;
  2152. var Vector2 = /** @class */ (function () {
  2153. /**
  2154. * Creates a new Vector2 from the passed x and y coordinates.
  2155. */
  2156. function Vector2(x, y) {
  2157. this.x = x;
  2158. this.y = y;
  2159. }
  2160. /**
  2161. * Returns a string with the Vector2 coordinates.
  2162. */
  2163. Vector2.prototype.toString = function () {
  2164. return "{X: " + this.x + " Y:" + this.y + "}";
  2165. };
  2166. /**
  2167. * Returns the string "Vector2"
  2168. */
  2169. Vector2.prototype.getClassName = function () {
  2170. return "Vector2";
  2171. };
  2172. /**
  2173. * Returns the Vector2 hash code as a number.
  2174. */
  2175. Vector2.prototype.getHashCode = function () {
  2176. var hash = this.x || 0;
  2177. hash = (hash * 397) ^ (this.y || 0);
  2178. return hash;
  2179. };
  2180. // Operators
  2181. /**
  2182. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2183. * Returns the Vector2.
  2184. */
  2185. Vector2.prototype.toArray = function (array, index) {
  2186. if (index === void 0) { index = 0; }
  2187. array[index] = this.x;
  2188. array[index + 1] = this.y;
  2189. return this;
  2190. };
  2191. /**
  2192. * Returns a new array with 2 elements : the Vector2 coordinates.
  2193. */
  2194. Vector2.prototype.asArray = function () {
  2195. var result = new Array();
  2196. this.toArray(result, 0);
  2197. return result;
  2198. };
  2199. /**
  2200. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2201. * Returns the updated Vector2.
  2202. */
  2203. Vector2.prototype.copyFrom = function (source) {
  2204. this.x = source.x;
  2205. this.y = source.y;
  2206. return this;
  2207. };
  2208. /**
  2209. * Sets the Vector2 coordinates with the passed floats.
  2210. * Returns the updated Vector2.
  2211. */
  2212. Vector2.prototype.copyFromFloats = function (x, y) {
  2213. this.x = x;
  2214. this.y = y;
  2215. return this;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed floats.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.set = function (x, y) {
  2222. return this.copyFromFloats(x, y);
  2223. };
  2224. /**
  2225. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2226. */
  2227. Vector2.prototype.add = function (otherVector) {
  2228. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2229. };
  2230. /**
  2231. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2232. * Returns the Vector2.
  2233. */
  2234. Vector2.prototype.addToRef = function (otherVector, result) {
  2235. result.x = this.x + otherVector.x;
  2236. result.y = this.y + otherVector.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2241. * Returns the updated Vector2.
  2242. */
  2243. Vector2.prototype.addInPlace = function (otherVector) {
  2244. this.x += otherVector.x;
  2245. this.y += otherVector.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2250. */
  2251. Vector2.prototype.addVector3 = function (otherVector) {
  2252. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2253. };
  2254. /**
  2255. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2256. */
  2257. Vector2.prototype.subtract = function (otherVector) {
  2258. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2259. };
  2260. /**
  2261. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2262. * Returns the Vector2.
  2263. */
  2264. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2265. result.x = this.x - otherVector.x;
  2266. result.y = this.y - otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2271. * Returns the updated Vector2.
  2272. */
  2273. Vector2.prototype.subtractInPlace = function (otherVector) {
  2274. this.x -= otherVector.x;
  2275. this.y -= otherVector.y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2280. * Returns the updated Vector2.
  2281. */
  2282. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2283. this.x *= otherVector.x;
  2284. this.y *= otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2289. */
  2290. Vector2.prototype.multiply = function (otherVector) {
  2291. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2292. };
  2293. /**
  2294. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2295. * Returns the Vector2.
  2296. */
  2297. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2298. result.x = this.x * otherVector.x;
  2299. result.y = this.y * otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2304. */
  2305. Vector2.prototype.multiplyByFloats = function (x, y) {
  2306. return new Vector2(this.x * x, this.y * y);
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2310. */
  2311. Vector2.prototype.divide = function (otherVector) {
  2312. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.divideToRef = function (otherVector, result) {
  2319. result.x = this.x / otherVector.x;
  2320. result.y = this.y / otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Divides the current Vector3 coordinates by the passed ones.
  2325. * Returns the updated Vector3.
  2326. */
  2327. Vector2.prototype.divideInPlace = function (otherVector) {
  2328. return this.divideToRef(otherVector, this);
  2329. };
  2330. /**
  2331. * Returns a new Vector2 with current Vector2 negated coordinates.
  2332. */
  2333. Vector2.prototype.negate = function () {
  2334. return new Vector2(-this.x, -this.y);
  2335. };
  2336. /**
  2337. * Multiply the Vector2 coordinates by scale.
  2338. * Returns the updated Vector2.
  2339. */
  2340. Vector2.prototype.scaleInPlace = function (scale) {
  2341. this.x *= scale;
  2342. this.y *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2347. */
  2348. Vector2.prototype.scale = function (scale) {
  2349. return new Vector2(this.x * scale, this.y * scale);
  2350. };
  2351. /**
  2352. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2353. */
  2354. Vector2.prototype.equals = function (otherVector) {
  2355. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2356. };
  2357. /**
  2358. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2359. */
  2360. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2361. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2362. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2363. };
  2364. // Properties
  2365. /**
  2366. * Returns the vector length (float).
  2367. */
  2368. Vector2.prototype.length = function () {
  2369. return Math.sqrt(this.x * this.x + this.y * this.y);
  2370. };
  2371. /**
  2372. * Returns the vector squared length (float);
  2373. */
  2374. Vector2.prototype.lengthSquared = function () {
  2375. return (this.x * this.x + this.y * this.y);
  2376. };
  2377. // Methods
  2378. /**
  2379. * Normalize the vector.
  2380. * Returns the updated Vector2.
  2381. */
  2382. Vector2.prototype.normalize = function () {
  2383. var len = this.length();
  2384. if (len === 0)
  2385. return this;
  2386. var num = 1.0 / len;
  2387. this.x *= num;
  2388. this.y *= num;
  2389. return this;
  2390. };
  2391. /**
  2392. * Returns a new Vector2 copied from the Vector2.
  2393. */
  2394. Vector2.prototype.clone = function () {
  2395. return new Vector2(this.x, this.y);
  2396. };
  2397. // Statics
  2398. /**
  2399. * Returns a new Vector2(0, 0)
  2400. */
  2401. Vector2.Zero = function () {
  2402. return new Vector2(0, 0);
  2403. };
  2404. /**
  2405. * Returns a new Vector2(1, 1)
  2406. */
  2407. Vector2.One = function () {
  2408. return new Vector2(1, 1);
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set from the passed index element of the passed array.
  2412. */
  2413. Vector2.FromArray = function (array, offset) {
  2414. if (offset === void 0) { offset = 0; }
  2415. return new Vector2(array[offset], array[offset + 1]);
  2416. };
  2417. /**
  2418. * Sets "result" from the passed index element of the passed array.
  2419. */
  2420. Vector2.FromArrayToRef = function (array, offset, result) {
  2421. result.x = array[offset];
  2422. result.y = array[offset + 1];
  2423. };
  2424. /**
  2425. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2426. */
  2427. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2428. var squared = amount * amount;
  2429. var cubed = amount * squared;
  2430. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2431. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2432. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2433. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2434. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2435. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2436. return new Vector2(x, y);
  2437. };
  2438. /**
  2439. * 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".
  2440. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2441. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2442. */
  2443. Vector2.Clamp = function (value, min, max) {
  2444. var x = value.x;
  2445. x = (x > max.x) ? max.x : x;
  2446. x = (x < min.x) ? min.x : x;
  2447. var y = value.y;
  2448. y = (y > max.y) ? max.y : y;
  2449. y = (y < min.y) ? min.y : y;
  2450. return new Vector2(x, y);
  2451. };
  2452. /**
  2453. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2454. */
  2455. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2456. var squared = amount * amount;
  2457. var cubed = amount * squared;
  2458. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2459. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2460. var part3 = (cubed - (2.0 * squared)) + amount;
  2461. var part4 = cubed - squared;
  2462. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2463. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2464. return new Vector2(x, y);
  2465. };
  2466. /**
  2467. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2468. */
  2469. Vector2.Lerp = function (start, end, amount) {
  2470. var x = start.x + ((end.x - start.x) * amount);
  2471. var y = start.y + ((end.y - start.y) * amount);
  2472. return new Vector2(x, y);
  2473. };
  2474. /**
  2475. * Returns the dot product (float) of the vector "left" and the vector "right".
  2476. */
  2477. Vector2.Dot = function (left, right) {
  2478. return left.x * right.x + left.y * right.y;
  2479. };
  2480. /**
  2481. * Returns a new Vector2 equal to the normalized passed vector.
  2482. */
  2483. Vector2.Normalize = function (vector) {
  2484. var newVector = vector.clone();
  2485. newVector.normalize();
  2486. return newVector;
  2487. };
  2488. /**
  2489. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2490. */
  2491. Vector2.Minimize = function (left, right) {
  2492. var x = (left.x < right.x) ? left.x : right.x;
  2493. var y = (left.y < right.y) ? left.y : right.y;
  2494. return new Vector2(x, y);
  2495. };
  2496. /**
  2497. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2498. */
  2499. Vector2.Maximize = function (left, right) {
  2500. var x = (left.x > right.x) ? left.x : right.x;
  2501. var y = (left.y > right.y) ? left.y : right.y;
  2502. return new Vector2(x, y);
  2503. };
  2504. /**
  2505. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2506. */
  2507. Vector2.Transform = function (vector, transformation) {
  2508. var r = Vector2.Zero();
  2509. Vector2.TransformToRef(vector, transformation, r);
  2510. return r;
  2511. };
  2512. /**
  2513. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2514. */
  2515. Vector2.TransformToRef = function (vector, transformation, result) {
  2516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2518. result.x = x;
  2519. result.y = y;
  2520. };
  2521. /**
  2522. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2523. */
  2524. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2525. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2526. var sign = a < 0 ? -1 : 1;
  2527. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2528. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2529. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2530. };
  2531. /**
  2532. * Returns the distance (float) between the vectors "value1" and "value2".
  2533. */
  2534. Vector2.Distance = function (value1, value2) {
  2535. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2536. };
  2537. /**
  2538. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2539. */
  2540. Vector2.DistanceSquared = function (value1, value2) {
  2541. var x = value1.x - value2.x;
  2542. var y = value1.y - value2.y;
  2543. return (x * x) + (y * y);
  2544. };
  2545. /**
  2546. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2547. */
  2548. Vector2.Center = function (value1, value2) {
  2549. var center = value1.add(value2);
  2550. center.scaleInPlace(0.5);
  2551. return center;
  2552. };
  2553. /**
  2554. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2555. */
  2556. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2557. var l2 = Vector2.DistanceSquared(segA, segB);
  2558. if (l2 === 0.0) {
  2559. return Vector2.Distance(p, segA);
  2560. }
  2561. var v = segB.subtract(segA);
  2562. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2563. var proj = segA.add(v.multiplyByFloats(t, t));
  2564. return Vector2.Distance(p, proj);
  2565. };
  2566. return Vector2;
  2567. }());
  2568. BABYLON.Vector2 = Vector2;
  2569. /**
  2570. * Classed used to store (x,y,z) vector representation
  2571. * A Vector3 is the main object used in 3D geometry
  2572. * It can represent etiher the coordinates of a point the space, either a direction
  2573. * Reminder: Babylon.js uses a left handed forward facing system
  2574. */
  2575. var Vector3 = /** @class */ (function () {
  2576. /**
  2577. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2578. * @param x defines the first coordinates (on X axis)
  2579. * @param y defines the second coordinates (on Y axis)
  2580. * @param z defines the third coordinates (on Z axis)
  2581. */
  2582. function Vector3(
  2583. /**
  2584. * Defines the first coordinates (on X axis)
  2585. */
  2586. x,
  2587. /**
  2588. * Defines the second coordinates (on Y axis)
  2589. */
  2590. y,
  2591. /**
  2592. * Defines the third coordinates (on Z axis)
  2593. */
  2594. z) {
  2595. this.x = x;
  2596. this.y = y;
  2597. this.z = z;
  2598. }
  2599. /**
  2600. * Creates a string representation of the Vector3
  2601. * @returns a string with the Vector3 coordinates.
  2602. */
  2603. Vector3.prototype.toString = function () {
  2604. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2605. };
  2606. /**
  2607. * Gets the class name
  2608. * @returns the string "Vector3"
  2609. */
  2610. Vector3.prototype.getClassName = function () {
  2611. return "Vector3";
  2612. };
  2613. /**
  2614. * Creates the Vector3 hash code
  2615. * @returns a number which tends to be unique between Vector3 instances
  2616. */
  2617. Vector3.prototype.getHashCode = function () {
  2618. var hash = this.x || 0;
  2619. hash = (hash * 397) ^ (this.y || 0);
  2620. hash = (hash * 397) ^ (this.z || 0);
  2621. return hash;
  2622. };
  2623. // Operators
  2624. /**
  2625. * Creates an array containing three elements : the coordinates of the Vector3
  2626. * @returns a new array of numbers
  2627. */
  2628. Vector3.prototype.asArray = function () {
  2629. var result = [];
  2630. this.toArray(result, 0);
  2631. return result;
  2632. };
  2633. /**
  2634. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2635. * @param array defines the destination array
  2636. * @param index defines the offset in the destination array
  2637. * @returns the current Vector3
  2638. */
  2639. Vector3.prototype.toArray = function (array, index) {
  2640. if (index === void 0) { index = 0; }
  2641. array[index] = this.x;
  2642. array[index + 1] = this.y;
  2643. array[index + 2] = this.z;
  2644. return this;
  2645. };
  2646. /**
  2647. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2648. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2649. */
  2650. Vector3.prototype.toQuaternion = function () {
  2651. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2652. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2653. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2654. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2655. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2656. var cosy = Math.cos(this.y * 0.5);
  2657. var siny = Math.sin(this.y * 0.5);
  2658. result.x = coszMinusx * siny;
  2659. result.y = -sinzMinusx * siny;
  2660. result.z = sinxPlusz * cosy;
  2661. result.w = cosxPlusz * cosy;
  2662. return result;
  2663. };
  2664. /**
  2665. * Adds the passed vector to the current Vector3
  2666. * @param otherVector defines the second operand
  2667. * @returns the current updated Vector3
  2668. */
  2669. Vector3.prototype.addInPlace = function (otherVector) {
  2670. this.x += otherVector.x;
  2671. this.y += otherVector.y;
  2672. this.z += otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2677. * @param otherVector defines the second operand
  2678. * @returns the resulting Vector3
  2679. */
  2680. Vector3.prototype.add = function (otherVector) {
  2681. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2682. };
  2683. /**
  2684. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2685. * @param otherVector defines the second operand
  2686. * @param result defines the Vector3 object where to store the result
  2687. * @returns the current Vector3
  2688. */
  2689. Vector3.prototype.addToRef = function (otherVector, result) {
  2690. result.x = this.x + otherVector.x;
  2691. result.y = this.y + otherVector.y;
  2692. result.z = this.z + otherVector.z;
  2693. return this;
  2694. };
  2695. /**
  2696. * Subtract the passed vector from the current Vector3
  2697. * @param otherVector defines the second operand
  2698. * @returns the current updated Vector3
  2699. */
  2700. Vector3.prototype.subtractInPlace = function (otherVector) {
  2701. this.x -= otherVector.x;
  2702. this.y -= otherVector.y;
  2703. this.z -= otherVector.z;
  2704. return this;
  2705. };
  2706. /**
  2707. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2708. * @param otherVector defines the second operand
  2709. * @returns the resulting Vector3
  2710. */
  2711. Vector3.prototype.subtract = function (otherVector) {
  2712. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2713. };
  2714. /**
  2715. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2716. * @param otherVector defines the second operand
  2717. * @param result defines the Vector3 object where to store the result
  2718. * @returns the current Vector3
  2719. */
  2720. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2721. result.x = this.x - otherVector.x;
  2722. result.y = this.y - otherVector.y;
  2723. result.z = this.z - otherVector.z;
  2724. return this;
  2725. };
  2726. /**
  2727. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2728. * @param x defines the x coordinate of the operand
  2729. * @param y defines the y coordinate of the operand
  2730. * @param z defines the z coordinate of the operand
  2731. * @returns the resulting Vector3
  2732. */
  2733. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2734. return new Vector3(this.x - x, this.y - y, this.z - z);
  2735. };
  2736. /**
  2737. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2738. * @param x defines the x coordinate of the operand
  2739. * @param y defines the y coordinate of the operand
  2740. * @param z defines the z coordinate of the operand
  2741. * @param result defines the Vector3 object where to store the result
  2742. * @returns the current Vector3
  2743. */
  2744. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2745. result.x = this.x - x;
  2746. result.y = this.y - y;
  2747. result.z = this.z - z;
  2748. return this;
  2749. };
  2750. /**
  2751. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2752. * @returns a new Vector3
  2753. */
  2754. Vector3.prototype.negate = function () {
  2755. return new Vector3(-this.x, -this.y, -this.z);
  2756. };
  2757. /**
  2758. * Multiplies the Vector3 coordinates by the float "scale"
  2759. * @param scale defines the multiplier factor
  2760. * @returns the current updated Vector3
  2761. */
  2762. Vector3.prototype.scaleInPlace = function (scale) {
  2763. this.x *= scale;
  2764. this.y *= scale;
  2765. this.z *= scale;
  2766. return this;
  2767. };
  2768. /**
  2769. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2770. * @param scale defines the multiplier factor
  2771. * @returns a new Vector3
  2772. */
  2773. Vector3.prototype.scale = function (scale) {
  2774. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2775. };
  2776. /**
  2777. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2778. * @param scale defines the multiplier factor
  2779. * @param result defines the Vector3 object where to store the result
  2780. * @returns the current Vector3
  2781. */
  2782. Vector3.prototype.scaleToRef = function (scale, result) {
  2783. result.x = this.x * scale;
  2784. result.y = this.y * scale;
  2785. result.z = this.z * scale;
  2786. return this;
  2787. };
  2788. /**
  2789. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2790. * @param otherVector defines the second operand
  2791. * @returns true if both vectors are equals
  2792. */
  2793. Vector3.prototype.equals = function (otherVector) {
  2794. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2795. };
  2796. /**
  2797. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2798. * @param otherVector defines the second operand
  2799. * @param epsilon defines the minimal distance to define values as equals
  2800. * @returns true if both vectors are distant less than epsilon
  2801. */
  2802. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2803. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2804. 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);
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 coordinates equals the passed floats
  2808. * @param x defines the x coordinate of the operand
  2809. * @param y defines the y coordinate of the operand
  2810. * @param z defines the z coordinate of the operand
  2811. * @returns true if both vectors are equals
  2812. */
  2813. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2814. return this.x === x && this.y === y && this.z === z;
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the passed ones
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2822. this.x *= otherVector.x;
  2823. this.y *= otherVector.y;
  2824. this.z *= otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the new Vector3
  2831. */
  2832. Vector3.prototype.multiply = function (otherVector) {
  2833. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2834. };
  2835. /**
  2836. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2842. result.x = this.x * otherVector.x;
  2843. result.y = this.y * otherVector.y;
  2844. result.z = this.z * otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2849. * @param x defines the x coordinate of the operand
  2850. * @param y defines the y coordinate of the operand
  2851. * @param z defines the z coordinate of the operand
  2852. * @returns the new Vector3
  2853. */
  2854. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2855. return new Vector3(this.x * x, this.y * y, this.z * z);
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2859. * @param otherVector defines the second operand
  2860. * @returns the new Vector3
  2861. */
  2862. Vector3.prototype.divide = function (otherVector) {
  2863. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2864. };
  2865. /**
  2866. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2867. * @param otherVector defines the second operand
  2868. * @param result defines the Vector3 object where to store the result
  2869. * @returns the current Vector3
  2870. */
  2871. Vector3.prototype.divideToRef = function (otherVector, result) {
  2872. result.x = this.x / otherVector.x;
  2873. result.y = this.y / otherVector.y;
  2874. result.z = this.z / otherVector.z;
  2875. return this;
  2876. };
  2877. /**
  2878. * Divides the current Vector3 coordinates by the passed ones.
  2879. * @param otherVector defines the second operand
  2880. * @returns the current updated Vector3
  2881. */
  2882. Vector3.prototype.divideInPlace = function (otherVector) {
  2883. return this.divideToRef(otherVector, this);
  2884. };
  2885. /**
  2886. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2887. * @param other defines the second operand
  2888. * @returns the current updated Vector3
  2889. */
  2890. Vector3.prototype.minimizeInPlace = function (other) {
  2891. if (other.x < this.x)
  2892. this.x = other.x;
  2893. if (other.y < this.y)
  2894. this.y = other.y;
  2895. if (other.z < this.z)
  2896. this.z = other.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2901. * @param other defines the second operand
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.maximizeInPlace = function (other) {
  2905. if (other.x > this.x)
  2906. this.x = other.x;
  2907. if (other.y > this.y)
  2908. this.y = other.y;
  2909. if (other.z > this.z)
  2910. this.z = other.z;
  2911. return this;
  2912. };
  2913. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2914. /**
  2915. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2916. */
  2917. get: function () {
  2918. var absX = Math.abs(this.x);
  2919. var absY = Math.abs(this.y);
  2920. if (absX !== absY) {
  2921. return true;
  2922. }
  2923. var absZ = Math.abs(this.z);
  2924. if (absX !== absZ) {
  2925. return true;
  2926. }
  2927. if (absY !== absZ) {
  2928. return true;
  2929. }
  2930. return false;
  2931. },
  2932. enumerable: true,
  2933. configurable: true
  2934. });
  2935. // Properties
  2936. /**
  2937. * Gets the length of the Vector3
  2938. * @returns the length of the Vecto3
  2939. */
  2940. Vector3.prototype.length = function () {
  2941. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2942. };
  2943. /**
  2944. * Gets the squared length of the Vector3
  2945. * @returns squared length of the Vector3
  2946. */
  2947. Vector3.prototype.lengthSquared = function () {
  2948. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2949. };
  2950. /**
  2951. * Normalize the current Vector3.
  2952. * Please note that this is an in place operation.
  2953. * @returns the current updated Vector3
  2954. */
  2955. Vector3.prototype.normalize = function () {
  2956. var len = this.length();
  2957. if (len === 0 || len === 1.0)
  2958. return this;
  2959. var num = 1.0 / len;
  2960. this.x *= num;
  2961. this.y *= num;
  2962. this.z *= num;
  2963. return this;
  2964. };
  2965. /**
  2966. * Normalize the current Vector3 to a new vector
  2967. * @returns the new Vector3
  2968. */
  2969. Vector3.prototype.normalizeToNew = function () {
  2970. var normalized = new Vector3(0, 0, 0);
  2971. this.normalizeToRef(normalized);
  2972. return normalized;
  2973. };
  2974. /**
  2975. * Normalize the current Vector3 to the reference
  2976. * @param reference define the Vector3 to update
  2977. * @returns the updated Vector3
  2978. */
  2979. Vector3.prototype.normalizeToRef = function (reference) {
  2980. var len = this.length();
  2981. if (len === 0 || len === 1.0) {
  2982. reference.set(this.x, this.y, this.z);
  2983. return reference;
  2984. }
  2985. var scale = 1.0 / len;
  2986. this.scaleToRef(scale, reference);
  2987. return reference;
  2988. };
  2989. /**
  2990. * Creates a new Vector3 copied from the current Vector3
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.clone = function () {
  2994. return new Vector3(this.x, this.y, this.z);
  2995. };
  2996. /**
  2997. * Copies the passed vector coordinates to the current Vector3 ones
  2998. * @param source defines the source Vector3
  2999. * @returns the current updated Vector3
  3000. */
  3001. Vector3.prototype.copyFrom = function (source) {
  3002. this.x = source.x;
  3003. this.y = source.y;
  3004. this.z = source.z;
  3005. return this;
  3006. };
  3007. /**
  3008. * Copies the passed floats to the current Vector3 coordinates
  3009. * @param x defines the x coordinate of the operand
  3010. * @param y defines the y coordinate of the operand
  3011. * @param z defines the z coordinate of the operand
  3012. * @returns the current updated Vector3
  3013. */
  3014. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3015. this.x = x;
  3016. this.y = y;
  3017. this.z = z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Copies the passed floats to the current Vector3 coordinates
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.set = function (x, y, z) {
  3028. return this.copyFromFloats(x, y, z);
  3029. };
  3030. // Statics
  3031. /**
  3032. * Get the clip factor between two vectors
  3033. * @param vector0 defines the first operand
  3034. * @param vector1 defines the second operand
  3035. * @param axis defines the axis to use
  3036. * @param size defines the size along the axis
  3037. * @returns the clip factor
  3038. */
  3039. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3040. var d0 = Vector3.Dot(vector0, axis) - size;
  3041. var d1 = Vector3.Dot(vector1, axis) - size;
  3042. var s = d0 / (d0 - d1);
  3043. return s;
  3044. };
  3045. /**
  3046. * Get angle between two vectors
  3047. * @param vector0 angle between vector0 and vector1
  3048. * @param vector1 angle between vector0 and vector1
  3049. * @param normal direction of the normal
  3050. * @return the angle between vector0 and vector1
  3051. */
  3052. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3053. var v0 = vector0.clone().normalize();
  3054. var v1 = vector1.clone().normalize();
  3055. var dot = Vector3.Dot(v0, v1);
  3056. var n = Vector3.Cross(v0, v1);
  3057. if (Vector3.Dot(n, normal) > 0) {
  3058. return Math.acos(dot);
  3059. }
  3060. return -Math.acos(dot);
  3061. };
  3062. /**
  3063. * Returns a new Vector3 set from the index "offset" of the passed array
  3064. * @param array defines the source array
  3065. * @param offset defines the offset in the source array
  3066. * @returns the new Vector3
  3067. */
  3068. Vector3.FromArray = function (array, offset) {
  3069. if (!offset) {
  3070. offset = 0;
  3071. }
  3072. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3073. };
  3074. /**
  3075. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3076. * This function is deprecated. Use FromArray instead
  3077. * @param array defines the source array
  3078. * @param offset defines the offset in the source array
  3079. * @returns the new Vector3
  3080. */
  3081. Vector3.FromFloatArray = function (array, offset) {
  3082. return Vector3.FromArray(array, offset);
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3086. * @param array defines the source array
  3087. * @param offset defines the offset in the source array
  3088. * @param result defines the Vector3 where to store the result
  3089. */
  3090. Vector3.FromArrayToRef = function (array, offset, result) {
  3091. result.x = array[offset];
  3092. result.y = array[offset + 1];
  3093. result.z = array[offset + 2];
  3094. };
  3095. /**
  3096. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3097. * This function is deprecated. Use FromArrayToRef instead.
  3098. * @param array defines the source array
  3099. * @param offset defines the offset in the source array
  3100. * @param result defines the Vector3 where to store the result
  3101. */
  3102. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3103. return Vector3.FromArrayToRef(array, offset, result);
  3104. };
  3105. /**
  3106. * Sets the passed vector "result" with the passed floats.
  3107. * @param x defines the x coordinate of the source
  3108. * @param y defines the y coordinate of the source
  3109. * @param z defines the z coordinate of the source
  3110. * @param result defines the Vector3 where to store the result
  3111. */
  3112. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3113. result.x = x;
  3114. result.y = y;
  3115. result.z = z;
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3119. * @returns a new empty Vector3
  3120. */
  3121. Vector3.Zero = function () {
  3122. return new Vector3(0.0, 0.0, 0.0);
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3126. * @returns a new unit Vector3
  3127. */
  3128. Vector3.One = function () {
  3129. return new Vector3(1.0, 1.0, 1.0);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3133. * @returns a new up Vector3
  3134. */
  3135. Vector3.Up = function () {
  3136. return new Vector3(0.0, 1.0, 0.0);
  3137. };
  3138. /**
  3139. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3140. * @returns a new forward Vector3
  3141. */
  3142. Vector3.Forward = function () {
  3143. return new Vector3(0.0, 0.0, 1.0);
  3144. };
  3145. /**
  3146. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3147. * @returns a new right Vector3
  3148. */
  3149. Vector3.Right = function () {
  3150. return new Vector3(1.0, 0.0, 0.0);
  3151. };
  3152. /**
  3153. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3154. * @returns a new left Vector3
  3155. */
  3156. Vector3.Left = function () {
  3157. return new Vector3(-1.0, 0.0, 0.0);
  3158. };
  3159. /**
  3160. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3161. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3162. * @param vector defines the Vector3 to transform
  3163. * @param transformation defines the transformation matrix
  3164. * @returns the transformed Vector3
  3165. */
  3166. Vector3.TransformCoordinates = function (vector, transformation) {
  3167. var result = Vector3.Zero();
  3168. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3169. return result;
  3170. };
  3171. /**
  3172. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3173. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3174. * @param vector defines the Vector3 to transform
  3175. * @param transformation defines the transformation matrix
  3176. * @param result defines the Vector3 where to store the result
  3177. */
  3178. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3179. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3180. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3181. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3182. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3183. result.x = x / w;
  3184. result.y = y / w;
  3185. result.z = z / w;
  3186. };
  3187. /**
  3188. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3189. * This method computes tranformed coordinates only, not transformed direction vectors
  3190. * @param x define the x coordinate of the source vector
  3191. * @param y define the y coordinate of the source vector
  3192. * @param z define the z coordinate of the source vector
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3197. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3198. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3199. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3200. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3201. result.x = rx / rw;
  3202. result.y = ry / rw;
  3203. result.z = rz / rw;
  3204. };
  3205. /**
  3206. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3207. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3208. * @param vector defines the Vector3 to transform
  3209. * @param transformation defines the transformation matrix
  3210. * @returns the new Vector3
  3211. */
  3212. Vector3.TransformNormal = function (vector, transformation) {
  3213. var result = Vector3.Zero();
  3214. Vector3.TransformNormalToRef(vector, transformation, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3219. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3220. * @param vector defines the Vector3 to transform
  3221. * @param transformation defines the transformation matrix
  3222. * @param result defines the Vector3 where to store the result
  3223. */
  3224. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3228. result.x = x;
  3229. result.y = y;
  3230. result.z = z;
  3231. };
  3232. /**
  3233. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3234. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3235. * @param x define the x coordinate of the source vector
  3236. * @param y define the y coordinate of the source vector
  3237. * @param z define the z coordinate of the source vector
  3238. * @param transformation defines the transformation matrix
  3239. * @param result defines the Vector3 where to store the result
  3240. */
  3241. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3242. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3243. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3244. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3248. * @param value1 defines the first control point
  3249. * @param value2 defines the second control point
  3250. * @param value3 defines the third control point
  3251. * @param value4 defines the fourth control point
  3252. * @param amount defines the amount on the spline to use
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3256. var squared = amount * amount;
  3257. var cubed = amount * squared;
  3258. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3259. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3260. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3261. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3262. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3263. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3264. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3265. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3266. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3267. return new Vector3(x, y, z);
  3268. };
  3269. /**
  3270. * 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"
  3271. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3272. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3273. * @param value defines the current value
  3274. * @param min defines the lower range value
  3275. * @param max defines the upper range value
  3276. * @returns the new Vector3
  3277. */
  3278. Vector3.Clamp = function (value, min, max) {
  3279. var x = value.x;
  3280. x = (x > max.x) ? max.x : x;
  3281. x = (x < min.x) ? min.x : x;
  3282. var y = value.y;
  3283. y = (y > max.y) ? max.y : y;
  3284. y = (y < min.y) ? min.y : y;
  3285. var z = value.z;
  3286. z = (z > max.z) ? max.z : z;
  3287. z = (z < min.z) ? min.z : z;
  3288. return new Vector3(x, y, z);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3292. * @param value1 defines the first control point
  3293. * @param tangent1 defines the first tangent vector
  3294. * @param value2 defines the second control point
  3295. * @param tangent2 defines the second tangent vector
  3296. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3297. * @returns the new Vector3
  3298. */
  3299. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3300. var squared = amount * amount;
  3301. var cubed = amount * squared;
  3302. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3303. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3304. var part3 = (cubed - (2.0 * squared)) + amount;
  3305. var part4 = cubed - squared;
  3306. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3307. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3308. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3309. return new Vector3(x, y, z);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3313. * @param start defines the start value
  3314. * @param end defines the end value
  3315. * @param amount max defines amount between both (between 0 and 1)
  3316. * @returns the new Vector3
  3317. */
  3318. Vector3.Lerp = function (start, end, amount) {
  3319. var result = new Vector3(0, 0, 0);
  3320. Vector3.LerpToRef(start, end, amount, result);
  3321. return result;
  3322. };
  3323. /**
  3324. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3325. * @param start defines the start value
  3326. * @param end defines the end value
  3327. * @param amount max defines amount between both (between 0 and 1)
  3328. * @param result defines the Vector3 where to store the result
  3329. */
  3330. Vector3.LerpToRef = function (start, end, amount, result) {
  3331. result.x = start.x + ((end.x - start.x) * amount);
  3332. result.y = start.y + ((end.y - start.y) * amount);
  3333. result.z = start.z + ((end.z - start.z) * amount);
  3334. };
  3335. /**
  3336. * Returns the dot product (float) between the vectors "left" and "right"
  3337. * @param left defines the left operand
  3338. * @param right defines the right operand
  3339. * @returns the dot product
  3340. */
  3341. Vector3.Dot = function (left, right) {
  3342. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3346. * The cross product is then orthogonal to both "left" and "right"
  3347. * @param left defines the left operand
  3348. * @param right defines the right operand
  3349. * @returns the cross product
  3350. */
  3351. Vector3.Cross = function (left, right) {
  3352. var result = Vector3.Zero();
  3353. Vector3.CrossToRef(left, right, result);
  3354. return result;
  3355. };
  3356. /**
  3357. * Sets the passed vector "result" with the cross product of "left" and "right"
  3358. * The cross product is then orthogonal to both "left" and "right"
  3359. * @param left defines the left operand
  3360. * @param right defines the right operand
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.CrossToRef = function (left, right, result) {
  3364. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3365. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3366. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3367. result.copyFrom(MathTmp.Vector3[0]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 as the normalization of the passed vector
  3371. * @param vector defines the Vector3 to normalize
  3372. * @returns the new Vector3
  3373. */
  3374. Vector3.Normalize = function (vector) {
  3375. var result = Vector3.Zero();
  3376. Vector3.NormalizeToRef(vector, result);
  3377. return result;
  3378. };
  3379. /**
  3380. * Sets the passed vector "result" with the normalization of the passed first vector
  3381. * @param vector defines the Vector3 to normalize
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.NormalizeToRef = function (vector, result) {
  3385. result.copyFrom(vector);
  3386. result.normalize();
  3387. };
  3388. /**
  3389. * Project a Vector3 onto screen space
  3390. * @param vector defines the Vector3 to project
  3391. * @param world defines the world matrix to use
  3392. * @param transform defines the transform (view x projection) matrix to use
  3393. * @param viewport defines the screen viewport to use
  3394. * @returns the new Vector3
  3395. */
  3396. Vector3.Project = function (vector, world, transform, viewport) {
  3397. var cw = viewport.width;
  3398. var ch = viewport.height;
  3399. var cx = viewport.x;
  3400. var cy = viewport.y;
  3401. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3402. 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);
  3403. var matrix = MathTmp.Matrix[0];
  3404. world.multiplyToRef(transform, matrix);
  3405. matrix.multiplyToRef(viewportMatrix, matrix);
  3406. return Vector3.TransformCoordinates(vector, matrix);
  3407. };
  3408. /**
  3409. * Unproject from screen space to object space
  3410. * @param source defines the screen space Vector3 to use
  3411. * @param viewportWidth defines the current width of the viewport
  3412. * @param viewportHeight defines the current height of the viewport
  3413. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3414. * @param transform defines the transform (view x projection) matrix to use
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3418. var matrix = MathTmp.Matrix[0];
  3419. world.multiplyToRef(transform, matrix);
  3420. matrix.invert();
  3421. source.x = source.x / viewportWidth * 2 - 1;
  3422. source.y = -(source.y / viewportHeight * 2 - 1);
  3423. var vector = Vector3.TransformCoordinates(source, matrix);
  3424. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3425. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3426. vector = vector.scale(1.0 / num);
  3427. }
  3428. return vector;
  3429. };
  3430. /**
  3431. * Unproject from screen space to object space
  3432. * @param source defines the screen space Vector3 to use
  3433. * @param viewportWidth defines the current width of the viewport
  3434. * @param viewportHeight defines the current height of the viewport
  3435. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3436. * @param view defines the view matrix to use
  3437. * @param projection defines the projection matrix to use
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3441. var result = Vector3.Zero();
  3442. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Unproject from screen space to object space
  3447. * @param source defines the screen space Vector3 to use
  3448. * @param viewportWidth defines the current width of the viewport
  3449. * @param viewportHeight defines the current height of the viewport
  3450. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3451. * @param view defines the view matrix to use
  3452. * @param projection defines the projection matrix to use
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3456. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3457. };
  3458. /**
  3459. * Unproject from screen space to object space
  3460. * @param sourceX defines the screen space x coordinate to use
  3461. * @param sourceY defines the screen space y coordinate to use
  3462. * @param sourceZ defines the screen space z coordinate to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param view defines the view matrix to use
  3467. * @param projection defines the projection matrix to use
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3471. var matrix = MathTmp.Matrix[0];
  3472. world.multiplyToRef(view, matrix);
  3473. matrix.multiplyToRef(projection, matrix);
  3474. matrix.invert();
  3475. var screenSource = MathTmp.Vector3[0];
  3476. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3477. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3478. screenSource.z = 2 * sourceZ - 1.0;
  3479. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3480. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3481. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3482. result.scaleInPlace(1.0 / num);
  3483. }
  3484. };
  3485. /**
  3486. * Gets the minimal coordinate values between two Vector3
  3487. * @param left defines the first operand
  3488. * @param right defines the second operand
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Minimize = function (left, right) {
  3492. var min = left.clone();
  3493. min.minimizeInPlace(right);
  3494. return min;
  3495. };
  3496. /**
  3497. * Gets the maximal coordinate values between two Vector3
  3498. * @param left defines the first operand
  3499. * @param right defines the second operand
  3500. * @returns the new Vector3
  3501. */
  3502. Vector3.Maximize = function (left, right) {
  3503. var max = left.clone();
  3504. max.maximizeInPlace(right);
  3505. return max;
  3506. };
  3507. /**
  3508. * Returns the distance between the vectors "value1" and "value2"
  3509. * @param value1 defines the first operand
  3510. * @param value2 defines the second operand
  3511. * @returns the distance
  3512. */
  3513. Vector3.Distance = function (value1, value2) {
  3514. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3515. };
  3516. /**
  3517. * Returns the squared distance between the vectors "value1" and "value2"
  3518. * @param value1 defines the first operand
  3519. * @param value2 defines the second operand
  3520. * @returns the squared distance
  3521. */
  3522. Vector3.DistanceSquared = function (value1, value2) {
  3523. var x = value1.x - value2.x;
  3524. var y = value1.y - value2.y;
  3525. var z = value1.z - value2.z;
  3526. return (x * x) + (y * y) + (z * z);
  3527. };
  3528. /**
  3529. * Returns a new Vector3 located at the center between "value1" and "value2"
  3530. * @param value1 defines the first operand
  3531. * @param value2 defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Center = function (value1, value2) {
  3535. var center = value1.add(value2);
  3536. center.scaleInPlace(0.5);
  3537. return center;
  3538. };
  3539. /**
  3540. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3541. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3542. * to something in order to rotate it from its local system to the given target system
  3543. * Note: axis1, axis2 and axis3 are normalized during this operation
  3544. * @param axis1 defines the first axis
  3545. * @param axis2 defines the second axis
  3546. * @param axis3 defines the third axis
  3547. * @returns a new Vector3
  3548. */
  3549. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3550. var rotation = Vector3.Zero();
  3551. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3552. return rotation;
  3553. };
  3554. /**
  3555. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3556. * @param axis1 defines the first axis
  3557. * @param axis2 defines the second axis
  3558. * @param axis3 defines the third axis
  3559. * @param ref defines the Vector3 where to store the result
  3560. */
  3561. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3562. var quat = MathTmp.Quaternion[0];
  3563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3564. quat.toEulerAnglesToRef(ref);
  3565. };
  3566. return Vector3;
  3567. }());
  3568. BABYLON.Vector3 = Vector3;
  3569. //Vector4 class created for EulerAngle class conversion to Quaternion
  3570. var Vector4 = /** @class */ (function () {
  3571. /**
  3572. * Creates a Vector4 object from the passed floats.
  3573. */
  3574. function Vector4(x, y, z, w) {
  3575. this.x = x;
  3576. this.y = y;
  3577. this.z = z;
  3578. this.w = w;
  3579. }
  3580. /**
  3581. * Returns the string with the Vector4 coordinates.
  3582. */
  3583. Vector4.prototype.toString = function () {
  3584. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3585. };
  3586. /**
  3587. * Returns the string "Vector4".
  3588. */
  3589. Vector4.prototype.getClassName = function () {
  3590. return "Vector4";
  3591. };
  3592. /**
  3593. * Returns the Vector4 hash code.
  3594. */
  3595. Vector4.prototype.getHashCode = function () {
  3596. var hash = this.x || 0;
  3597. hash = (hash * 397) ^ (this.y || 0);
  3598. hash = (hash * 397) ^ (this.z || 0);
  3599. hash = (hash * 397) ^ (this.w || 0);
  3600. return hash;
  3601. };
  3602. // Operators
  3603. /**
  3604. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3605. */
  3606. Vector4.prototype.asArray = function () {
  3607. var result = new Array();
  3608. this.toArray(result, 0);
  3609. return result;
  3610. };
  3611. /**
  3612. * Populates the passed array from the passed index with the Vector4 coordinates.
  3613. * Returns the Vector4.
  3614. */
  3615. Vector4.prototype.toArray = function (array, index) {
  3616. if (index === undefined) {
  3617. index = 0;
  3618. }
  3619. array[index] = this.x;
  3620. array[index + 1] = this.y;
  3621. array[index + 2] = this.z;
  3622. array[index + 3] = this.w;
  3623. return this;
  3624. };
  3625. /**
  3626. * Adds the passed vector to the current Vector4.
  3627. * Returns the updated Vector4.
  3628. */
  3629. Vector4.prototype.addInPlace = function (otherVector) {
  3630. this.x += otherVector.x;
  3631. this.y += otherVector.y;
  3632. this.z += otherVector.z;
  3633. this.w += otherVector.w;
  3634. return this;
  3635. };
  3636. /**
  3637. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3638. */
  3639. Vector4.prototype.add = function (otherVector) {
  3640. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3641. };
  3642. /**
  3643. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3644. * Returns the current Vector4.
  3645. */
  3646. Vector4.prototype.addToRef = function (otherVector, result) {
  3647. result.x = this.x + otherVector.x;
  3648. result.y = this.y + otherVector.y;
  3649. result.z = this.z + otherVector.z;
  3650. result.w = this.w + otherVector.w;
  3651. return this;
  3652. };
  3653. /**
  3654. * Subtract in place the passed vector from the current Vector4.
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.subtractInPlace = function (otherVector) {
  3658. this.x -= otherVector.x;
  3659. this.y -= otherVector.y;
  3660. this.z -= otherVector.z;
  3661. this.w -= otherVector.w;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3666. */
  3667. Vector4.prototype.subtract = function (otherVector) {
  3668. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3675. result.x = this.x - otherVector.x;
  3676. result.y = this.y - otherVector.y;
  3677. result.z = this.z - otherVector.z;
  3678. result.w = this.w - otherVector.w;
  3679. return this;
  3680. };
  3681. /**
  3682. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3683. */
  3684. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3685. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3686. };
  3687. /**
  3688. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3689. * Returns the current Vector4.
  3690. */
  3691. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3692. result.x = this.x - x;
  3693. result.y = this.y - y;
  3694. result.z = this.z - z;
  3695. result.w = this.w - w;
  3696. return this;
  3697. };
  3698. /**
  3699. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3700. */
  3701. Vector4.prototype.negate = function () {
  3702. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3703. };
  3704. /**
  3705. * Multiplies the current Vector4 coordinates by scale (float).
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.scaleInPlace = function (scale) {
  3709. this.x *= scale;
  3710. this.y *= scale;
  3711. this.z *= scale;
  3712. this.w *= scale;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3717. */
  3718. Vector4.prototype.scale = function (scale) {
  3719. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3720. };
  3721. /**
  3722. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.scaleToRef = function (scale, result) {
  3726. result.x = this.x * scale;
  3727. result.y = this.y * scale;
  3728. result.z = this.z * scale;
  3729. result.w = this.w * scale;
  3730. return this;
  3731. };
  3732. /**
  3733. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3734. */
  3735. Vector4.prototype.equals = function (otherVector) {
  3736. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3737. };
  3738. /**
  3739. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3740. */
  3741. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3742. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3743. return otherVector
  3744. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3745. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3746. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3747. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3748. };
  3749. /**
  3750. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3751. */
  3752. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3753. return this.x === x && this.y === y && this.z === z && this.w === w;
  3754. };
  3755. /**
  3756. * Multiplies in place the current Vector4 by the passed one.
  3757. * Returns the updated Vector4.
  3758. */
  3759. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3760. this.x *= otherVector.x;
  3761. this.y *= otherVector.y;
  3762. this.z *= otherVector.z;
  3763. this.w *= otherVector.w;
  3764. return this;
  3765. };
  3766. /**
  3767. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3768. */
  3769. Vector4.prototype.multiply = function (otherVector) {
  3770. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3771. };
  3772. /**
  3773. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3774. * Returns the current Vector4.
  3775. */
  3776. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3777. result.x = this.x * otherVector.x;
  3778. result.y = this.y * otherVector.y;
  3779. result.z = this.z * otherVector.z;
  3780. result.w = this.w * otherVector.w;
  3781. return this;
  3782. };
  3783. /**
  3784. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3787. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3788. };
  3789. /**
  3790. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3791. */
  3792. Vector4.prototype.divide = function (otherVector) {
  3793. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3794. };
  3795. /**
  3796. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3797. * Returns the current Vector4.
  3798. */
  3799. Vector4.prototype.divideToRef = function (otherVector, result) {
  3800. result.x = this.x / otherVector.x;
  3801. result.y = this.y / otherVector.y;
  3802. result.z = this.z / otherVector.z;
  3803. result.w = this.w / otherVector.w;
  3804. return this;
  3805. };
  3806. /**
  3807. * Divides the current Vector3 coordinates by the passed ones.
  3808. * @returns the updated Vector3.
  3809. */
  3810. Vector4.prototype.divideInPlace = function (otherVector) {
  3811. return this.divideToRef(otherVector, this);
  3812. };
  3813. /**
  3814. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3815. * @param other defines the second operand
  3816. * @returns the current updated Vector4
  3817. */
  3818. Vector4.prototype.minimizeInPlace = function (other) {
  3819. if (other.x < this.x)
  3820. this.x = other.x;
  3821. if (other.y < this.y)
  3822. this.y = other.y;
  3823. if (other.z < this.z)
  3824. this.z = other.z;
  3825. if (other.w < this.w)
  3826. this.w = other.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3831. * @param other defines the second operand
  3832. * @returns the current updated Vector4
  3833. */
  3834. Vector4.prototype.maximizeInPlace = function (other) {
  3835. if (other.x > this.x)
  3836. this.x = other.x;
  3837. if (other.y > this.y)
  3838. this.y = other.y;
  3839. if (other.z > this.z)
  3840. this.z = other.z;
  3841. if (other.w > this.w)
  3842. this.w = other.w;
  3843. return this;
  3844. };
  3845. // Properties
  3846. /**
  3847. * Returns the Vector4 length (float).
  3848. */
  3849. Vector4.prototype.length = function () {
  3850. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3851. };
  3852. /**
  3853. * Returns the Vector4 squared length (float).
  3854. */
  3855. Vector4.prototype.lengthSquared = function () {
  3856. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3857. };
  3858. // Methods
  3859. /**
  3860. * Normalizes in place the Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.normalize = function () {
  3864. var len = this.length();
  3865. if (len === 0)
  3866. return this;
  3867. var num = 1.0 / len;
  3868. this.x *= num;
  3869. this.y *= num;
  3870. this.z *= num;
  3871. this.w *= num;
  3872. return this;
  3873. };
  3874. /**
  3875. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3876. */
  3877. Vector4.prototype.toVector3 = function () {
  3878. return new Vector3(this.x, this.y, this.z);
  3879. };
  3880. /**
  3881. * Returns a new Vector4 copied from the current one.
  3882. */
  3883. Vector4.prototype.clone = function () {
  3884. return new Vector4(this.x, this.y, this.z, this.w);
  3885. };
  3886. /**
  3887. * Updates the current Vector4 with the passed one coordinates.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.copyFrom = function (source) {
  3891. this.x = source.x;
  3892. this.y = source.y;
  3893. this.z = source.z;
  3894. this.w = source.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Updates the current Vector4 coordinates with the passed floats.
  3899. * Returns the updated Vector4.
  3900. */
  3901. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3902. this.x = x;
  3903. this.y = y;
  3904. this.z = z;
  3905. this.w = w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Updates the current Vector4 coordinates with the passed floats.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.set = function (x, y, z, w) {
  3913. return this.copyFromFloats(x, y, z, w);
  3914. };
  3915. // Statics
  3916. /**
  3917. * Returns a new Vector4 set from the starting index of the passed array.
  3918. */
  3919. Vector4.FromArray = function (array, offset) {
  3920. if (!offset) {
  3921. offset = 0;
  3922. }
  3923. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3924. };
  3925. /**
  3926. * Updates the passed vector "result" from the starting index of the passed array.
  3927. */
  3928. Vector4.FromArrayToRef = function (array, offset, result) {
  3929. result.x = array[offset];
  3930. result.y = array[offset + 1];
  3931. result.z = array[offset + 2];
  3932. result.w = array[offset + 3];
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3936. */
  3937. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3938. Vector4.FromArrayToRef(array, offset, result);
  3939. };
  3940. /**
  3941. * Updates the passed vector "result" coordinates from the passed floats.
  3942. */
  3943. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3944. result.x = x;
  3945. result.y = y;
  3946. result.z = z;
  3947. result.w = w;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3951. */
  3952. Vector4.Zero = function () {
  3953. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3957. */
  3958. Vector4.One = function () {
  3959. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3960. };
  3961. /**
  3962. * Returns a new normalized Vector4 from the passed one.
  3963. */
  3964. Vector4.Normalize = function (vector) {
  3965. var result = Vector4.Zero();
  3966. Vector4.NormalizeToRef(vector, result);
  3967. return result;
  3968. };
  3969. /**
  3970. * Updates the passed vector "result" from the normalization of the passed one.
  3971. */
  3972. Vector4.NormalizeToRef = function (vector, result) {
  3973. result.copyFrom(vector);
  3974. result.normalize();
  3975. };
  3976. Vector4.Minimize = function (left, right) {
  3977. var min = left.clone();
  3978. min.minimizeInPlace(right);
  3979. return min;
  3980. };
  3981. Vector4.Maximize = function (left, right) {
  3982. var max = left.clone();
  3983. max.maximizeInPlace(right);
  3984. return max;
  3985. };
  3986. /**
  3987. * Returns the distance (float) between the vectors "value1" and "value2".
  3988. */
  3989. Vector4.Distance = function (value1, value2) {
  3990. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3991. };
  3992. /**
  3993. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3994. */
  3995. Vector4.DistanceSquared = function (value1, value2) {
  3996. var x = value1.x - value2.x;
  3997. var y = value1.y - value2.y;
  3998. var z = value1.z - value2.z;
  3999. var w = value1.w - value2.w;
  4000. return (x * x) + (y * y) + (z * z) + (w * w);
  4001. };
  4002. /**
  4003. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4004. */
  4005. Vector4.Center = function (value1, value2) {
  4006. var center = value1.add(value2);
  4007. center.scaleInPlace(0.5);
  4008. return center;
  4009. };
  4010. /**
  4011. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4012. * This methods computes transformed normalized direction vectors only.
  4013. */
  4014. Vector4.TransformNormal = function (vector, transformation) {
  4015. var result = Vector4.Zero();
  4016. Vector4.TransformNormalToRef(vector, transformation, result);
  4017. return result;
  4018. };
  4019. /**
  4020. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4021. * This methods computes transformed normalized direction vectors only.
  4022. */
  4023. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4024. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4025. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4026. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4027. result.x = x;
  4028. result.y = y;
  4029. result.z = z;
  4030. result.w = vector.w;
  4031. };
  4032. /**
  4033. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4034. * This methods computes transformed normalized direction vectors only.
  4035. */
  4036. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4037. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4038. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4039. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4040. result.w = w;
  4041. };
  4042. return Vector4;
  4043. }());
  4044. BABYLON.Vector4 = Vector4;
  4045. var Size = /** @class */ (function () {
  4046. /**
  4047. * Creates a Size object from the passed width and height (floats).
  4048. */
  4049. function Size(width, height) {
  4050. this.width = width;
  4051. this.height = height;
  4052. }
  4053. // Returns a string with the Size width and height.
  4054. Size.prototype.toString = function () {
  4055. return "{W: " + this.width + ", H: " + this.height + "}";
  4056. };
  4057. /**
  4058. * Returns the string "Size"
  4059. */
  4060. Size.prototype.getClassName = function () {
  4061. return "Size";
  4062. };
  4063. /**
  4064. * Returns the Size hash code.
  4065. */
  4066. Size.prototype.getHashCode = function () {
  4067. var hash = this.width || 0;
  4068. hash = (hash * 397) ^ (this.height || 0);
  4069. return hash;
  4070. };
  4071. /**
  4072. * Updates the current size from the passed one.
  4073. * Returns the updated Size.
  4074. */
  4075. Size.prototype.copyFrom = function (src) {
  4076. this.width = src.width;
  4077. this.height = src.height;
  4078. };
  4079. /**
  4080. * Updates in place the current Size from the passed floats.
  4081. * Returns the updated Size.
  4082. */
  4083. Size.prototype.copyFromFloats = function (width, height) {
  4084. this.width = width;
  4085. this.height = height;
  4086. return this;
  4087. };
  4088. /**
  4089. * Updates in place the current Size from the passed floats.
  4090. * Returns the updated Size.
  4091. */
  4092. Size.prototype.set = function (width, height) {
  4093. return this.copyFromFloats(width, height);
  4094. };
  4095. /**
  4096. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4097. */
  4098. Size.prototype.multiplyByFloats = function (w, h) {
  4099. return new Size(this.width * w, this.height * h);
  4100. };
  4101. /**
  4102. * Returns a new Size copied from the passed one.
  4103. */
  4104. Size.prototype.clone = function () {
  4105. return new Size(this.width, this.height);
  4106. };
  4107. /**
  4108. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4109. */
  4110. Size.prototype.equals = function (other) {
  4111. if (!other) {
  4112. return false;
  4113. }
  4114. return (this.width === other.width) && (this.height === other.height);
  4115. };
  4116. Object.defineProperty(Size.prototype, "surface", {
  4117. /**
  4118. * Returns the surface of the Size : width * height (float).
  4119. */
  4120. get: function () {
  4121. return this.width * this.height;
  4122. },
  4123. enumerable: true,
  4124. configurable: true
  4125. });
  4126. /**
  4127. * Returns a new Size set to (0.0, 0.0)
  4128. */
  4129. Size.Zero = function () {
  4130. return new Size(0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Size set as the addition result of the current Size and the passed one.
  4134. */
  4135. Size.prototype.add = function (otherSize) {
  4136. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4137. return r;
  4138. };
  4139. /**
  4140. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4141. */
  4142. Size.prototype.subtract = function (otherSize) {
  4143. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4144. return r;
  4145. };
  4146. /**
  4147. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4148. */
  4149. Size.Lerp = function (start, end, amount) {
  4150. var w = start.width + ((end.width - start.width) * amount);
  4151. var h = start.height + ((end.height - start.height) * amount);
  4152. return new Size(w, h);
  4153. };
  4154. return Size;
  4155. }());
  4156. BABYLON.Size = Size;
  4157. var Quaternion = /** @class */ (function () {
  4158. /**
  4159. * Creates a new Quaternion from the passed floats.
  4160. */
  4161. function Quaternion(x, y, z, w) {
  4162. if (x === void 0) { x = 0.0; }
  4163. if (y === void 0) { y = 0.0; }
  4164. if (z === void 0) { z = 0.0; }
  4165. if (w === void 0) { w = 1.0; }
  4166. this.x = x;
  4167. this.y = y;
  4168. this.z = z;
  4169. this.w = w;
  4170. }
  4171. /**
  4172. * Returns a string with the Quaternion coordinates.
  4173. */
  4174. Quaternion.prototype.toString = function () {
  4175. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4176. };
  4177. /**
  4178. * Returns the string "Quaternion".
  4179. */
  4180. Quaternion.prototype.getClassName = function () {
  4181. return "Quaternion";
  4182. };
  4183. /**
  4184. * Returns the Quaternion hash code.
  4185. */
  4186. Quaternion.prototype.getHashCode = function () {
  4187. var hash = this.x || 0;
  4188. hash = (hash * 397) ^ (this.y || 0);
  4189. hash = (hash * 397) ^ (this.z || 0);
  4190. hash = (hash * 397) ^ (this.w || 0);
  4191. return hash;
  4192. };
  4193. /**
  4194. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4195. */
  4196. Quaternion.prototype.asArray = function () {
  4197. return [this.x, this.y, this.z, this.w];
  4198. };
  4199. /**
  4200. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4201. */
  4202. Quaternion.prototype.equals = function (otherQuaternion) {
  4203. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4204. };
  4205. /**
  4206. * Returns a new Quaternion copied from the current one.
  4207. */
  4208. Quaternion.prototype.clone = function () {
  4209. return new Quaternion(this.x, this.y, this.z, this.w);
  4210. };
  4211. /**
  4212. * Updates the current Quaternion from the passed one coordinates.
  4213. * Returns the updated Quaterion.
  4214. */
  4215. Quaternion.prototype.copyFrom = function (other) {
  4216. this.x = other.x;
  4217. this.y = other.y;
  4218. this.z = other.z;
  4219. this.w = other.w;
  4220. return this;
  4221. };
  4222. /**
  4223. * Updates the current Quaternion from the passed float coordinates.
  4224. * Returns the updated Quaterion.
  4225. */
  4226. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4227. this.x = x;
  4228. this.y = y;
  4229. this.z = z;
  4230. this.w = w;
  4231. return this;
  4232. };
  4233. /**
  4234. * Updates the current Quaternion from the passed float coordinates.
  4235. * Returns the updated Quaterion.
  4236. */
  4237. Quaternion.prototype.set = function (x, y, z, w) {
  4238. return this.copyFromFloats(x, y, z, w);
  4239. };
  4240. /**
  4241. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4242. */
  4243. Quaternion.prototype.add = function (other) {
  4244. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4245. };
  4246. /**
  4247. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4248. */
  4249. Quaternion.prototype.subtract = function (other) {
  4250. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4251. };
  4252. /**
  4253. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4254. */
  4255. Quaternion.prototype.scale = function (value) {
  4256. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4260. */
  4261. Quaternion.prototype.multiply = function (q1) {
  4262. var result = new Quaternion(0, 0, 0, 1.0);
  4263. this.multiplyToRef(q1, result);
  4264. return result;
  4265. };
  4266. /**
  4267. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4268. * Returns the current Quaternion.
  4269. */
  4270. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4271. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4272. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4273. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4274. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4275. result.copyFromFloats(x, y, z, w);
  4276. return this;
  4277. };
  4278. /**
  4279. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4280. * Returns the updated Quaternion.
  4281. */
  4282. Quaternion.prototype.multiplyInPlace = function (q1) {
  4283. this.multiplyToRef(q1, this);
  4284. return this;
  4285. };
  4286. /**
  4287. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4288. * Returns the current Quaternion.
  4289. */
  4290. Quaternion.prototype.conjugateToRef = function (ref) {
  4291. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4292. return this;
  4293. };
  4294. /**
  4295. * Conjugates in place the current Quaternion.
  4296. * Returns the updated Quaternion.
  4297. */
  4298. Quaternion.prototype.conjugateInPlace = function () {
  4299. this.x *= -1;
  4300. this.y *= -1;
  4301. this.z *= -1;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4306. */
  4307. Quaternion.prototype.conjugate = function () {
  4308. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4309. return result;
  4310. };
  4311. /**
  4312. * Returns the Quaternion length (float).
  4313. */
  4314. Quaternion.prototype.length = function () {
  4315. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4316. };
  4317. /**
  4318. * Normalize in place the current Quaternion.
  4319. * Returns the updated Quaternion.
  4320. */
  4321. Quaternion.prototype.normalize = function () {
  4322. var length = 1.0 / this.length();
  4323. this.x *= length;
  4324. this.y *= length;
  4325. this.z *= length;
  4326. this.w *= length;
  4327. return this;
  4328. };
  4329. /**
  4330. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4331. */
  4332. Quaternion.prototype.toEulerAngles = function (order) {
  4333. if (order === void 0) { order = "YZX"; }
  4334. var result = Vector3.Zero();
  4335. this.toEulerAnglesToRef(result, order);
  4336. return result;
  4337. };
  4338. /**
  4339. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4340. * Returns the current Quaternion.
  4341. */
  4342. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4343. if (order === void 0) { order = "YZX"; }
  4344. var qz = this.z;
  4345. var qx = this.x;
  4346. var qy = this.y;
  4347. var qw = this.w;
  4348. var sqw = qw * qw;
  4349. var sqz = qz * qz;
  4350. var sqx = qx * qx;
  4351. var sqy = qy * qy;
  4352. var zAxisY = qy * qz - qx * qw;
  4353. var limit = .4999999;
  4354. if (zAxisY < -limit) {
  4355. result.y = 2 * Math.atan2(qy, qw);
  4356. result.x = Math.PI / 2;
  4357. result.z = 0;
  4358. }
  4359. else if (zAxisY > limit) {
  4360. result.y = 2 * Math.atan2(qy, qw);
  4361. result.x = -Math.PI / 2;
  4362. result.z = 0;
  4363. }
  4364. else {
  4365. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4366. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4367. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4368. }
  4369. return this;
  4370. };
  4371. /**
  4372. * Updates the passed rotation matrix with the current Quaternion values.
  4373. * Returns the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toRotationMatrix = function (result) {
  4376. var xx = this.x * this.x;
  4377. var yy = this.y * this.y;
  4378. var zz = this.z * this.z;
  4379. var xy = this.x * this.y;
  4380. var zw = this.z * this.w;
  4381. var zx = this.z * this.x;
  4382. var yw = this.y * this.w;
  4383. var yz = this.y * this.z;
  4384. var xw = this.x * this.w;
  4385. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4386. result.m[1] = 2.0 * (xy + zw);
  4387. result.m[2] = 2.0 * (zx - yw);
  4388. result.m[3] = 0;
  4389. result.m[4] = 2.0 * (xy - zw);
  4390. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4391. result.m[6] = 2.0 * (yz + xw);
  4392. result.m[7] = 0;
  4393. result.m[8] = 2.0 * (zx + yw);
  4394. result.m[9] = 2.0 * (yz - xw);
  4395. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4396. result.m[11] = 0;
  4397. result.m[12] = 0;
  4398. result.m[13] = 0;
  4399. result.m[14] = 0;
  4400. result.m[15] = 1.0;
  4401. result._markAsUpdated();
  4402. return this;
  4403. };
  4404. /**
  4405. * Updates the current Quaternion from the passed rotation matrix values.
  4406. * Returns the updated Quaternion.
  4407. */
  4408. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4409. Quaternion.FromRotationMatrixToRef(matrix, this);
  4410. return this;
  4411. };
  4412. // Statics
  4413. /**
  4414. * Returns a new Quaternion set from the passed rotation matrix values.
  4415. */
  4416. Quaternion.FromRotationMatrix = function (matrix) {
  4417. var result = new Quaternion();
  4418. Quaternion.FromRotationMatrixToRef(matrix, result);
  4419. return result;
  4420. };
  4421. /**
  4422. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4423. */
  4424. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4425. var data = matrix.m;
  4426. var m11 = data[0], m12 = data[4], m13 = data[8];
  4427. var m21 = data[1], m22 = data[5], m23 = data[9];
  4428. var m31 = data[2], m32 = data[6], m33 = data[10];
  4429. var trace = m11 + m22 + m33;
  4430. var s;
  4431. if (trace > 0) {
  4432. s = 0.5 / Math.sqrt(trace + 1.0);
  4433. result.w = 0.25 / s;
  4434. result.x = (m32 - m23) * s;
  4435. result.y = (m13 - m31) * s;
  4436. result.z = (m21 - m12) * s;
  4437. }
  4438. else if (m11 > m22 && m11 > m33) {
  4439. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4440. result.w = (m32 - m23) / s;
  4441. result.x = 0.25 * s;
  4442. result.y = (m12 + m21) / s;
  4443. result.z = (m13 + m31) / s;
  4444. }
  4445. else if (m22 > m33) {
  4446. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4447. result.w = (m13 - m31) / s;
  4448. result.x = (m12 + m21) / s;
  4449. result.y = 0.25 * s;
  4450. result.z = (m23 + m32) / s;
  4451. }
  4452. else {
  4453. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4454. result.w = (m21 - m12) / s;
  4455. result.x = (m13 + m31) / s;
  4456. result.y = (m23 + m32) / s;
  4457. result.z = 0.25 * s;
  4458. }
  4459. };
  4460. /**
  4461. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4462. */
  4463. Quaternion.Zero = function () {
  4464. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4465. };
  4466. /**
  4467. * Returns a new Quaternion as the inverted current Quaternion.
  4468. */
  4469. Quaternion.Inverse = function (q) {
  4470. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4471. };
  4472. /**
  4473. * Returns the identity Quaternion.
  4474. */
  4475. Quaternion.Identity = function () {
  4476. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4477. };
  4478. Quaternion.IsIdentity = function (quaternion) {
  4479. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4480. };
  4481. /**
  4482. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4483. */
  4484. Quaternion.RotationAxis = function (axis, angle) {
  4485. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4486. };
  4487. /**
  4488. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4489. */
  4490. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4491. var sin = Math.sin(angle / 2);
  4492. axis.normalize();
  4493. result.w = Math.cos(angle / 2);
  4494. result.x = axis.x * sin;
  4495. result.y = axis.y * sin;
  4496. result.z = axis.z * sin;
  4497. return result;
  4498. };
  4499. /**
  4500. * Retuns a new Quaternion set from the starting index of the passed array.
  4501. */
  4502. Quaternion.FromArray = function (array, offset) {
  4503. if (!offset) {
  4504. offset = 0;
  4505. }
  4506. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4507. };
  4508. /**
  4509. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4510. */
  4511. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4512. var q = new Quaternion();
  4513. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4514. return q;
  4515. };
  4516. /**
  4517. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4518. */
  4519. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4520. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4521. var halfRoll = roll * 0.5;
  4522. var halfPitch = pitch * 0.5;
  4523. var halfYaw = yaw * 0.5;
  4524. var sinRoll = Math.sin(halfRoll);
  4525. var cosRoll = Math.cos(halfRoll);
  4526. var sinPitch = Math.sin(halfPitch);
  4527. var cosPitch = Math.cos(halfPitch);
  4528. var sinYaw = Math.sin(halfYaw);
  4529. var cosYaw = Math.cos(halfYaw);
  4530. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4531. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4532. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4533. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4534. };
  4535. /**
  4536. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4537. */
  4538. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4539. var result = new Quaternion();
  4540. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4545. */
  4546. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4547. // Produces a quaternion from Euler angles in the z-x-z orientation
  4548. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4549. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4550. var halfBeta = beta * 0.5;
  4551. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4552. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4553. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4554. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4555. };
  4556. /**
  4557. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4558. * cf to Vector3.RotationFromAxis() documentation.
  4559. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4560. */
  4561. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4562. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4564. return quat;
  4565. };
  4566. /**
  4567. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4568. * cf to Vector3.RotationFromAxis() documentation.
  4569. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4570. */
  4571. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4572. var rotMat = MathTmp.Matrix[0];
  4573. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4574. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4575. };
  4576. Quaternion.Slerp = function (left, right, amount) {
  4577. var result = Quaternion.Identity();
  4578. Quaternion.SlerpToRef(left, right, amount, result);
  4579. return result;
  4580. };
  4581. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4582. var num2;
  4583. var num3;
  4584. var num = amount;
  4585. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4586. var flag = false;
  4587. if (num4 < 0) {
  4588. flag = true;
  4589. num4 = -num4;
  4590. }
  4591. if (num4 > 0.999999) {
  4592. num3 = 1 - num;
  4593. num2 = flag ? -num : num;
  4594. }
  4595. else {
  4596. var num5 = Math.acos(num4);
  4597. var num6 = (1.0 / Math.sin(num5));
  4598. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4599. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4600. }
  4601. result.x = (num3 * left.x) + (num2 * right.x);
  4602. result.y = (num3 * left.y) + (num2 * right.y);
  4603. result.z = (num3 * left.z) + (num2 * right.z);
  4604. result.w = (num3 * left.w) + (num2 * right.w);
  4605. };
  4606. /**
  4607. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4608. */
  4609. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4610. var squared = amount * amount;
  4611. var cubed = amount * squared;
  4612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4614. var part3 = (cubed - (2.0 * squared)) + amount;
  4615. var part4 = cubed - squared;
  4616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4619. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4620. return new Quaternion(x, y, z, w);
  4621. };
  4622. return Quaternion;
  4623. }());
  4624. BABYLON.Quaternion = Quaternion;
  4625. var Matrix = /** @class */ (function () {
  4626. function Matrix() {
  4627. this._isIdentity = false;
  4628. this._isIdentityDirty = true;
  4629. this.m = new Float32Array(16);
  4630. this._markAsUpdated();
  4631. }
  4632. Matrix.prototype._markAsUpdated = function () {
  4633. this.updateFlag = Matrix._updateFlagSeed++;
  4634. this._isIdentityDirty = true;
  4635. };
  4636. // Properties
  4637. /**
  4638. * Boolean : True is the matrix is the identity matrix
  4639. */
  4640. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4641. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4642. if (this._isIdentityDirty) {
  4643. this._isIdentityDirty = false;
  4644. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4645. this._isIdentity = false;
  4646. }
  4647. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4648. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4649. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4650. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4651. this._isIdentity = false;
  4652. }
  4653. else {
  4654. this._isIdentity = true;
  4655. }
  4656. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4657. this._isIdentity = false;
  4658. }
  4659. }
  4660. return this._isIdentity;
  4661. };
  4662. /**
  4663. * Returns the matrix determinant (float).
  4664. */
  4665. Matrix.prototype.determinant = function () {
  4666. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4667. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4668. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4669. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4670. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4671. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4672. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4673. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4674. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4675. };
  4676. // Methods
  4677. /**
  4678. * Returns the matrix underlying array.
  4679. */
  4680. Matrix.prototype.toArray = function () {
  4681. return this.m;
  4682. };
  4683. /**
  4684. * Returns the matrix underlying array.
  4685. */
  4686. Matrix.prototype.asArray = function () {
  4687. return this.toArray();
  4688. };
  4689. /**
  4690. * Inverts in place the Matrix.
  4691. * Returns the Matrix inverted.
  4692. */
  4693. Matrix.prototype.invert = function () {
  4694. this.invertToRef(this);
  4695. return this;
  4696. };
  4697. /**
  4698. * Sets all the matrix elements to zero.
  4699. * Returns the Matrix.
  4700. */
  4701. Matrix.prototype.reset = function () {
  4702. for (var index = 0; index < 16; index++) {
  4703. this.m[index] = 0.0;
  4704. }
  4705. this._markAsUpdated();
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4710. */
  4711. Matrix.prototype.add = function (other) {
  4712. var result = new Matrix();
  4713. this.addToRef(other, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4718. * Returns the Matrix.
  4719. */
  4720. Matrix.prototype.addToRef = function (other, result) {
  4721. for (var index = 0; index < 16; index++) {
  4722. result.m[index] = this.m[index] + other.m[index];
  4723. }
  4724. result._markAsUpdated();
  4725. return this;
  4726. };
  4727. /**
  4728. * Adds in place the passed matrix to the current Matrix.
  4729. * Returns the updated Matrix.
  4730. */
  4731. Matrix.prototype.addToSelf = function (other) {
  4732. for (var index = 0; index < 16; index++) {
  4733. this.m[index] += other.m[index];
  4734. }
  4735. this._markAsUpdated();
  4736. return this;
  4737. };
  4738. /**
  4739. * Sets the passed matrix with the current inverted Matrix.
  4740. * Returns the unmodified current Matrix.
  4741. */
  4742. Matrix.prototype.invertToRef = function (other) {
  4743. var l1 = this.m[0];
  4744. var l2 = this.m[1];
  4745. var l3 = this.m[2];
  4746. var l4 = this.m[3];
  4747. var l5 = this.m[4];
  4748. var l6 = this.m[5];
  4749. var l7 = this.m[6];
  4750. var l8 = this.m[7];
  4751. var l9 = this.m[8];
  4752. var l10 = this.m[9];
  4753. var l11 = this.m[10];
  4754. var l12 = this.m[11];
  4755. var l13 = this.m[12];
  4756. var l14 = this.m[13];
  4757. var l15 = this.m[14];
  4758. var l16 = this.m[15];
  4759. var l17 = (l11 * l16) - (l12 * l15);
  4760. var l18 = (l10 * l16) - (l12 * l14);
  4761. var l19 = (l10 * l15) - (l11 * l14);
  4762. var l20 = (l9 * l16) - (l12 * l13);
  4763. var l21 = (l9 * l15) - (l11 * l13);
  4764. var l22 = (l9 * l14) - (l10 * l13);
  4765. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4766. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4767. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4768. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4769. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4770. var l28 = (l7 * l16) - (l8 * l15);
  4771. var l29 = (l6 * l16) - (l8 * l14);
  4772. var l30 = (l6 * l15) - (l7 * l14);
  4773. var l31 = (l5 * l16) - (l8 * l13);
  4774. var l32 = (l5 * l15) - (l7 * l13);
  4775. var l33 = (l5 * l14) - (l6 * l13);
  4776. var l34 = (l7 * l12) - (l8 * l11);
  4777. var l35 = (l6 * l12) - (l8 * l10);
  4778. var l36 = (l6 * l11) - (l7 * l10);
  4779. var l37 = (l5 * l12) - (l8 * l9);
  4780. var l38 = (l5 * l11) - (l7 * l9);
  4781. var l39 = (l5 * l10) - (l6 * l9);
  4782. other.m[0] = l23 * l27;
  4783. other.m[4] = l24 * l27;
  4784. other.m[8] = l25 * l27;
  4785. other.m[12] = l26 * l27;
  4786. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4787. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4788. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4789. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4790. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4791. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4792. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4793. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4794. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4795. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4796. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4797. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4798. other._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4806. this.m[12] = x;
  4807. this.m[13] = y;
  4808. this.m[14] = z;
  4809. this._markAsUpdated();
  4810. return this;
  4811. };
  4812. /**
  4813. * Inserts the translation vector in the current Matrix.
  4814. * Returns the updated Matrix.
  4815. */
  4816. Matrix.prototype.setTranslation = function (vector3) {
  4817. this.m[12] = vector3.x;
  4818. this.m[13] = vector3.y;
  4819. this.m[14] = vector3.z;
  4820. this._markAsUpdated();
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Vector3 as the extracted translation from the Matrix.
  4825. */
  4826. Matrix.prototype.getTranslation = function () {
  4827. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4828. };
  4829. /**
  4830. * Fill a Vector3 with the extracted translation from the Matrix.
  4831. */
  4832. Matrix.prototype.getTranslationToRef = function (result) {
  4833. result.x = this.m[12];
  4834. result.y = this.m[13];
  4835. result.z = this.m[14];
  4836. return this;
  4837. };
  4838. /**
  4839. * Remove rotation and scaling part from the Matrix.
  4840. * Returns the updated Matrix.
  4841. */
  4842. Matrix.prototype.removeRotationAndScaling = function () {
  4843. this.setRowFromFloats(0, 1, 0, 0, 0);
  4844. this.setRowFromFloats(1, 0, 1, 0, 0);
  4845. this.setRowFromFloats(2, 0, 0, 1, 0);
  4846. return this;
  4847. };
  4848. /**
  4849. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4850. */
  4851. Matrix.prototype.multiply = function (other) {
  4852. var result = new Matrix();
  4853. this.multiplyToRef(other, result);
  4854. return result;
  4855. };
  4856. /**
  4857. * Updates the current Matrix from the passed one values.
  4858. * Returns the updated Matrix.
  4859. */
  4860. Matrix.prototype.copyFrom = function (other) {
  4861. for (var index = 0; index < 16; index++) {
  4862. this.m[index] = other.m[index];
  4863. }
  4864. this._markAsUpdated();
  4865. return this;
  4866. };
  4867. /**
  4868. * Populates the passed array from the starting index with the Matrix values.
  4869. * Returns the Matrix.
  4870. */
  4871. Matrix.prototype.copyToArray = function (array, offset) {
  4872. if (offset === void 0) { offset = 0; }
  4873. for (var index = 0; index < 16; index++) {
  4874. array[offset + index] = this.m[index];
  4875. }
  4876. return this;
  4877. };
  4878. /**
  4879. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4880. */
  4881. Matrix.prototype.multiplyToRef = function (other, result) {
  4882. this.multiplyToArray(other, result.m, 0);
  4883. result._markAsUpdated();
  4884. return this;
  4885. };
  4886. /**
  4887. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4888. */
  4889. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4890. var tm0 = this.m[0];
  4891. var tm1 = this.m[1];
  4892. var tm2 = this.m[2];
  4893. var tm3 = this.m[3];
  4894. var tm4 = this.m[4];
  4895. var tm5 = this.m[5];
  4896. var tm6 = this.m[6];
  4897. var tm7 = this.m[7];
  4898. var tm8 = this.m[8];
  4899. var tm9 = this.m[9];
  4900. var tm10 = this.m[10];
  4901. var tm11 = this.m[11];
  4902. var tm12 = this.m[12];
  4903. var tm13 = this.m[13];
  4904. var tm14 = this.m[14];
  4905. var tm15 = this.m[15];
  4906. var om0 = other.m[0];
  4907. var om1 = other.m[1];
  4908. var om2 = other.m[2];
  4909. var om3 = other.m[3];
  4910. var om4 = other.m[4];
  4911. var om5 = other.m[5];
  4912. var om6 = other.m[6];
  4913. var om7 = other.m[7];
  4914. var om8 = other.m[8];
  4915. var om9 = other.m[9];
  4916. var om10 = other.m[10];
  4917. var om11 = other.m[11];
  4918. var om12 = other.m[12];
  4919. var om13 = other.m[13];
  4920. var om14 = other.m[14];
  4921. var om15 = other.m[15];
  4922. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4923. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4924. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4925. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4926. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4927. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4928. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4929. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4930. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4931. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4932. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4933. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4934. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4935. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4936. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4937. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4938. return this;
  4939. };
  4940. /**
  4941. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4942. */
  4943. Matrix.prototype.equals = function (value) {
  4944. return value &&
  4945. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4946. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4947. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4948. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4949. };
  4950. /**
  4951. * Returns a new Matrix from the current Matrix.
  4952. */
  4953. Matrix.prototype.clone = function () {
  4954. 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]);
  4955. };
  4956. /**
  4957. * Returns the string "Matrix"
  4958. */
  4959. Matrix.prototype.getClassName = function () {
  4960. return "Matrix";
  4961. };
  4962. /**
  4963. * Returns the Matrix hash code.
  4964. */
  4965. Matrix.prototype.getHashCode = function () {
  4966. var hash = this.m[0] || 0;
  4967. for (var i = 1; i < 16; i++) {
  4968. hash = (hash * 397) ^ (this.m[i] || 0);
  4969. }
  4970. return hash;
  4971. };
  4972. /**
  4973. * Decomposes the current Matrix into :
  4974. * - a scale vector3 passed as a reference to update,
  4975. * - a rotation quaternion passed as a reference to update,
  4976. * - a translation vector3 passed as a reference to update.
  4977. * Returns the true if operation was successful.
  4978. */
  4979. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4980. translation.x = this.m[12];
  4981. translation.y = this.m[13];
  4982. translation.z = this.m[14];
  4983. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4984. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4985. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4986. if (this.determinant() <= 0) {
  4987. scale.y *= -1;
  4988. }
  4989. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4990. rotation.x = 0;
  4991. rotation.y = 0;
  4992. rotation.z = 0;
  4993. rotation.w = 1;
  4994. return false;
  4995. }
  4996. 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]);
  4997. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4998. return true;
  4999. };
  5000. /**
  5001. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5002. * @param ref matrix to store the result
  5003. */
  5004. Matrix.prototype.toNormalMatrix = function (ref) {
  5005. this.invertToRef(ref);
  5006. ref.transpose();
  5007. var m = ref.m;
  5008. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5009. };
  5010. /**
  5011. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5012. */
  5013. Matrix.prototype.getRotationMatrix = function () {
  5014. var result = Matrix.Identity();
  5015. this.getRotationMatrixToRef(result);
  5016. return result;
  5017. };
  5018. /**
  5019. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5020. * Returns the current Matrix.
  5021. */
  5022. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5023. var m = this.m;
  5024. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5025. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5026. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5027. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5028. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5029. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5030. 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);
  5031. return this;
  5032. };
  5033. // Statics
  5034. /**
  5035. * Returns a new Matrix set from the starting index of the passed array.
  5036. */
  5037. Matrix.FromArray = function (array, offset) {
  5038. var result = new Matrix();
  5039. if (!offset) {
  5040. offset = 0;
  5041. }
  5042. Matrix.FromArrayToRef(array, offset, result);
  5043. return result;
  5044. };
  5045. /**
  5046. * Sets the passed "result" matrix from the starting index of the passed array.
  5047. */
  5048. Matrix.FromArrayToRef = function (array, offset, result) {
  5049. for (var index = 0; index < 16; index++) {
  5050. result.m[index] = array[index + offset];
  5051. }
  5052. result._markAsUpdated();
  5053. };
  5054. /**
  5055. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5056. */
  5057. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5058. for (var index = 0; index < 16; index++) {
  5059. result.m[index] = array[index + offset] * scale;
  5060. }
  5061. result._markAsUpdated();
  5062. };
  5063. /**
  5064. * Sets the passed matrix "result" with the 16 passed floats.
  5065. */
  5066. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5067. result.m[0] = initialM11;
  5068. result.m[1] = initialM12;
  5069. result.m[2] = initialM13;
  5070. result.m[3] = initialM14;
  5071. result.m[4] = initialM21;
  5072. result.m[5] = initialM22;
  5073. result.m[6] = initialM23;
  5074. result.m[7] = initialM24;
  5075. result.m[8] = initialM31;
  5076. result.m[9] = initialM32;
  5077. result.m[10] = initialM33;
  5078. result.m[11] = initialM34;
  5079. result.m[12] = initialM41;
  5080. result.m[13] = initialM42;
  5081. result.m[14] = initialM43;
  5082. result.m[15] = initialM44;
  5083. result._markAsUpdated();
  5084. };
  5085. /**
  5086. * Returns the index-th row of the current matrix as a new Vector4.
  5087. */
  5088. Matrix.prototype.getRow = function (index) {
  5089. if (index < 0 || index > 3) {
  5090. return null;
  5091. }
  5092. var i = index * 4;
  5093. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5094. };
  5095. /**
  5096. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5097. * Returns the updated Matrix.
  5098. */
  5099. Matrix.prototype.setRow = function (index, row) {
  5100. if (index < 0 || index > 3) {
  5101. return this;
  5102. }
  5103. var i = index * 4;
  5104. this.m[i + 0] = row.x;
  5105. this.m[i + 1] = row.y;
  5106. this.m[i + 2] = row.z;
  5107. this.m[i + 3] = row.w;
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Compute the transpose of the matrix.
  5113. * Returns a new Matrix.
  5114. */
  5115. Matrix.prototype.transpose = function () {
  5116. return Matrix.Transpose(this);
  5117. };
  5118. /**
  5119. * Compute the transpose of the matrix.
  5120. * Returns the current matrix.
  5121. */
  5122. Matrix.prototype.transposeToRef = function (result) {
  5123. Matrix.TransposeToRef(this, result);
  5124. return this;
  5125. };
  5126. /**
  5127. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5128. * Returns the updated Matrix.
  5129. */
  5130. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5131. if (index < 0 || index > 3) {
  5132. return this;
  5133. }
  5134. var i = index * 4;
  5135. this.m[i + 0] = x;
  5136. this.m[i + 1] = y;
  5137. this.m[i + 2] = z;
  5138. this.m[i + 3] = w;
  5139. this._markAsUpdated();
  5140. return this;
  5141. };
  5142. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5143. /**
  5144. * Static identity matrix to be used as readonly matrix
  5145. * Must not be updated.
  5146. */
  5147. get: function () {
  5148. return Matrix._identityReadOnly;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. /**
  5154. * Returns a new Matrix set from the 16 passed floats.
  5155. */
  5156. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5157. var result = new Matrix();
  5158. result.m[0] = initialM11;
  5159. result.m[1] = initialM12;
  5160. result.m[2] = initialM13;
  5161. result.m[3] = initialM14;
  5162. result.m[4] = initialM21;
  5163. result.m[5] = initialM22;
  5164. result.m[6] = initialM23;
  5165. result.m[7] = initialM24;
  5166. result.m[8] = initialM31;
  5167. result.m[9] = initialM32;
  5168. result.m[10] = initialM33;
  5169. result.m[11] = initialM34;
  5170. result.m[12] = initialM41;
  5171. result.m[13] = initialM42;
  5172. result.m[14] = initialM43;
  5173. result.m[15] = initialM44;
  5174. return result;
  5175. };
  5176. /**
  5177. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5178. */
  5179. Matrix.Compose = function (scale, rotation, translation) {
  5180. var result = Matrix.Identity();
  5181. Matrix.ComposeToRef(scale, rotation, translation, result);
  5182. return result;
  5183. };
  5184. /**
  5185. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5186. */
  5187. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5188. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5189. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5190. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5191. result.setTranslation(translation);
  5192. };
  5193. /**
  5194. * Returns a new indentity Matrix.
  5195. */
  5196. Matrix.Identity = function () {
  5197. 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);
  5198. };
  5199. /**
  5200. * Sets the passed "result" as an identity matrix.
  5201. */
  5202. Matrix.IdentityToRef = function (result) {
  5203. 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);
  5204. };
  5205. /**
  5206. * Returns a new zero Matrix.
  5207. */
  5208. Matrix.Zero = function () {
  5209. 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);
  5210. };
  5211. /**
  5212. * Returns a new rotation matrix for "angle" radians around the X axis.
  5213. */
  5214. Matrix.RotationX = function (angle) {
  5215. var result = new Matrix();
  5216. Matrix.RotationXToRef(angle, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix as the passed inverted one.
  5221. */
  5222. Matrix.Invert = function (source) {
  5223. var result = new Matrix();
  5224. source.invertToRef(result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5229. */
  5230. Matrix.RotationXToRef = function (angle, result) {
  5231. var s = Math.sin(angle);
  5232. var c = Math.cos(angle);
  5233. result.m[0] = 1.0;
  5234. result.m[15] = 1.0;
  5235. result.m[5] = c;
  5236. result.m[10] = c;
  5237. result.m[9] = -s;
  5238. result.m[6] = s;
  5239. result.m[1] = 0.0;
  5240. result.m[2] = 0.0;
  5241. result.m[3] = 0.0;
  5242. result.m[4] = 0.0;
  5243. result.m[7] = 0.0;
  5244. result.m[8] = 0.0;
  5245. result.m[11] = 0.0;
  5246. result.m[12] = 0.0;
  5247. result.m[13] = 0.0;
  5248. result.m[14] = 0.0;
  5249. result._markAsUpdated();
  5250. };
  5251. /**
  5252. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5253. */
  5254. Matrix.RotationY = function (angle) {
  5255. var result = new Matrix();
  5256. Matrix.RotationYToRef(angle, result);
  5257. return result;
  5258. };
  5259. /**
  5260. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5261. */
  5262. Matrix.RotationYToRef = function (angle, result) {
  5263. var s = Math.sin(angle);
  5264. var c = Math.cos(angle);
  5265. result.m[5] = 1.0;
  5266. result.m[15] = 1.0;
  5267. result.m[0] = c;
  5268. result.m[2] = -s;
  5269. result.m[8] = s;
  5270. result.m[10] = c;
  5271. result.m[1] = 0.0;
  5272. result.m[3] = 0.0;
  5273. result.m[4] = 0.0;
  5274. result.m[6] = 0.0;
  5275. result.m[7] = 0.0;
  5276. result.m[9] = 0.0;
  5277. result.m[11] = 0.0;
  5278. result.m[12] = 0.0;
  5279. result.m[13] = 0.0;
  5280. result.m[14] = 0.0;
  5281. result._markAsUpdated();
  5282. };
  5283. /**
  5284. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5285. */
  5286. Matrix.RotationZ = function (angle) {
  5287. var result = new Matrix();
  5288. Matrix.RotationZToRef(angle, result);
  5289. return result;
  5290. };
  5291. /**
  5292. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5293. */
  5294. Matrix.RotationZToRef = function (angle, result) {
  5295. var s = Math.sin(angle);
  5296. var c = Math.cos(angle);
  5297. result.m[10] = 1.0;
  5298. result.m[15] = 1.0;
  5299. result.m[0] = c;
  5300. result.m[1] = s;
  5301. result.m[4] = -s;
  5302. result.m[5] = c;
  5303. result.m[2] = 0.0;
  5304. result.m[3] = 0.0;
  5305. result.m[6] = 0.0;
  5306. result.m[7] = 0.0;
  5307. result.m[8] = 0.0;
  5308. result.m[9] = 0.0;
  5309. result.m[11] = 0.0;
  5310. result.m[12] = 0.0;
  5311. result.m[13] = 0.0;
  5312. result.m[14] = 0.0;
  5313. result._markAsUpdated();
  5314. };
  5315. /**
  5316. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5317. */
  5318. Matrix.RotationAxis = function (axis, angle) {
  5319. var result = Matrix.Zero();
  5320. Matrix.RotationAxisToRef(axis, angle, result);
  5321. return result;
  5322. };
  5323. /**
  5324. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5325. */
  5326. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5327. var s = Math.sin(-angle);
  5328. var c = Math.cos(-angle);
  5329. var c1 = 1 - c;
  5330. axis.normalize();
  5331. result.m[0] = (axis.x * axis.x) * c1 + c;
  5332. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5333. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5334. result.m[3] = 0.0;
  5335. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5336. result.m[5] = (axis.y * axis.y) * c1 + c;
  5337. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5338. result.m[7] = 0.0;
  5339. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5340. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5341. result.m[10] = (axis.z * axis.z) * c1 + c;
  5342. result.m[11] = 0.0;
  5343. result.m[15] = 1.0;
  5344. result._markAsUpdated();
  5345. };
  5346. /**
  5347. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5348. */
  5349. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5350. var result = new Matrix();
  5351. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5356. */
  5357. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5358. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5359. this._tempQuaternion.toRotationMatrix(result);
  5360. };
  5361. /**
  5362. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5363. */
  5364. Matrix.Scaling = function (x, y, z) {
  5365. var result = Matrix.Zero();
  5366. Matrix.ScalingToRef(x, y, z, result);
  5367. return result;
  5368. };
  5369. /**
  5370. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5371. */
  5372. Matrix.ScalingToRef = function (x, y, z, result) {
  5373. result.m[0] = x;
  5374. result.m[1] = 0.0;
  5375. result.m[2] = 0.0;
  5376. result.m[3] = 0.0;
  5377. result.m[4] = 0.0;
  5378. result.m[5] = y;
  5379. result.m[6] = 0.0;
  5380. result.m[7] = 0.0;
  5381. result.m[8] = 0.0;
  5382. result.m[9] = 0.0;
  5383. result.m[10] = z;
  5384. result.m[11] = 0.0;
  5385. result.m[12] = 0.0;
  5386. result.m[13] = 0.0;
  5387. result.m[14] = 0.0;
  5388. result.m[15] = 1.0;
  5389. result._markAsUpdated();
  5390. };
  5391. /**
  5392. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5393. */
  5394. Matrix.Translation = function (x, y, z) {
  5395. var result = Matrix.Identity();
  5396. Matrix.TranslationToRef(x, y, z, result);
  5397. return result;
  5398. };
  5399. /**
  5400. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5401. */
  5402. Matrix.TranslationToRef = function (x, y, z, result) {
  5403. 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);
  5404. };
  5405. /**
  5406. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5407. */
  5408. Matrix.Lerp = function (startValue, endValue, gradient) {
  5409. var result = Matrix.Zero();
  5410. for (var index = 0; index < 16; index++) {
  5411. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5412. }
  5413. result._markAsUpdated();
  5414. return result;
  5415. };
  5416. /**
  5417. * Returns a new Matrix whose values are computed by :
  5418. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5419. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5420. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5421. */
  5422. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5423. var startScale = new Vector3(0, 0, 0);
  5424. var startRotation = new Quaternion();
  5425. var startTranslation = new Vector3(0, 0, 0);
  5426. startValue.decompose(startScale, startRotation, startTranslation);
  5427. var endScale = new Vector3(0, 0, 0);
  5428. var endRotation = new Quaternion();
  5429. var endTranslation = new Vector3(0, 0, 0);
  5430. endValue.decompose(endScale, endRotation, endTranslation);
  5431. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5432. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5433. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5434. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5435. };
  5436. /**
  5437. * 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".
  5438. * This methods works for a Left-Handed system.
  5439. */
  5440. Matrix.LookAtLH = function (eye, target, up) {
  5441. var result = Matrix.Zero();
  5442. Matrix.LookAtLHToRef(eye, target, up, result);
  5443. return result;
  5444. };
  5445. /**
  5446. * 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".
  5447. * This methods works for a Left-Handed system.
  5448. */
  5449. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5450. // Z axis
  5451. target.subtractToRef(eye, this._zAxis);
  5452. this._zAxis.normalize();
  5453. // X axis
  5454. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5455. if (this._xAxis.lengthSquared() === 0) {
  5456. this._xAxis.x = 1.0;
  5457. }
  5458. else {
  5459. this._xAxis.normalize();
  5460. }
  5461. // Y axis
  5462. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5463. this._yAxis.normalize();
  5464. // Eye angles
  5465. var ex = -Vector3.Dot(this._xAxis, eye);
  5466. var ey = -Vector3.Dot(this._yAxis, eye);
  5467. var ez = -Vector3.Dot(this._zAxis, eye);
  5468. 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);
  5469. };
  5470. /**
  5471. * 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".
  5472. * This methods works for a Right-Handed system.
  5473. */
  5474. Matrix.LookAtRH = function (eye, target, up) {
  5475. var result = Matrix.Zero();
  5476. Matrix.LookAtRHToRef(eye, target, up, result);
  5477. return result;
  5478. };
  5479. /**
  5480. * 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".
  5481. * This methods works for a Left-Handed system.
  5482. */
  5483. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5484. // Z axis
  5485. eye.subtractToRef(target, this._zAxis);
  5486. this._zAxis.normalize();
  5487. // X axis
  5488. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5489. if (this._xAxis.lengthSquared() === 0) {
  5490. this._xAxis.x = 1.0;
  5491. }
  5492. else {
  5493. this._xAxis.normalize();
  5494. }
  5495. // Y axis
  5496. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5497. this._yAxis.normalize();
  5498. // Eye angles
  5499. var ex = -Vector3.Dot(this._xAxis, eye);
  5500. var ey = -Vector3.Dot(this._yAxis, eye);
  5501. var ez = -Vector3.Dot(this._zAxis, eye);
  5502. 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);
  5503. };
  5504. /**
  5505. * 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.
  5506. */
  5507. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5508. var matrix = Matrix.Zero();
  5509. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5510. return matrix;
  5511. };
  5512. /**
  5513. * 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.
  5514. */
  5515. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5516. var n = znear;
  5517. var f = zfar;
  5518. var a = 2.0 / width;
  5519. var b = 2.0 / height;
  5520. var c = 2.0 / (f - n);
  5521. var d = -(f + n) / (f - n);
  5522. 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);
  5523. };
  5524. /**
  5525. * 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.
  5526. */
  5527. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5528. var matrix = Matrix.Zero();
  5529. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5530. return matrix;
  5531. };
  5532. /**
  5533. * 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.
  5534. */
  5535. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5536. var n = znear;
  5537. var f = zfar;
  5538. var a = 2.0 / (right - left);
  5539. var b = 2.0 / (top - bottom);
  5540. var c = 2.0 / (f - n);
  5541. var d = -(f + n) / (f - n);
  5542. var i0 = (left + right) / (left - right);
  5543. var i1 = (top + bottom) / (bottom - top);
  5544. 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);
  5545. };
  5546. /**
  5547. * 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.
  5548. */
  5549. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5550. var matrix = Matrix.Zero();
  5551. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5552. return matrix;
  5553. };
  5554. /**
  5555. * 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.
  5556. */
  5557. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5558. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5559. result.m[10] *= -1.0;
  5560. };
  5561. /**
  5562. * 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.
  5563. */
  5564. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. var n = znear;
  5567. var f = zfar;
  5568. var a = 2.0 * n / width;
  5569. var b = 2.0 * n / height;
  5570. var c = (f + n) / (f - n);
  5571. var d = -2.0 * f * n / (f - n);
  5572. 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);
  5573. return matrix;
  5574. };
  5575. /**
  5576. * 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.
  5577. */
  5578. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5579. var matrix = Matrix.Zero();
  5580. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5581. return matrix;
  5582. };
  5583. /**
  5584. * 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.
  5585. */
  5586. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5588. var n = znear;
  5589. var f = zfar;
  5590. var t = 1.0 / (Math.tan(fov * 0.5));
  5591. var a = isVerticalFovFixed ? (t / aspect) : t;
  5592. var b = isVerticalFovFixed ? t : (t * aspect);
  5593. var c = (f + n) / (f - n);
  5594. var d = -2.0 * f * n / (f - n);
  5595. 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);
  5596. };
  5597. /**
  5598. * 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.
  5599. */
  5600. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5601. var matrix = Matrix.Zero();
  5602. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5603. return matrix;
  5604. };
  5605. /**
  5606. * 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.
  5607. */
  5608. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5609. //alternatively this could be expressed as:
  5610. // m = PerspectiveFovLHToRef
  5611. // m[10] *= -1.0;
  5612. // m[11] *= -1.0;
  5613. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5614. var n = znear;
  5615. var f = zfar;
  5616. var t = 1.0 / (Math.tan(fov * 0.5));
  5617. var a = isVerticalFovFixed ? (t / aspect) : t;
  5618. var b = isVerticalFovFixed ? t : (t * aspect);
  5619. var c = -(f + n) / (f - n);
  5620. var d = -2 * f * n / (f - n);
  5621. 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);
  5622. };
  5623. /**
  5624. * 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.
  5625. */
  5626. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5627. if (rightHanded === void 0) { rightHanded = false; }
  5628. var rightHandedFactor = rightHanded ? -1 : 1;
  5629. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5630. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5631. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5632. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5633. var xScale = 2.0 / (leftTan + rightTan);
  5634. var yScale = 2.0 / (upTan + downTan);
  5635. result.m[0] = xScale;
  5636. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5637. result.m[5] = yScale;
  5638. result.m[6] = result.m[7] = 0.0;
  5639. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5640. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5641. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5642. result.m[10] = -zfar / (znear - zfar);
  5643. result.m[11] = 1.0 * rightHandedFactor;
  5644. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5645. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5646. // result.m[14] = (znear * zfar) / (znear - zfar);
  5647. result._markAsUpdated();
  5648. };
  5649. /**
  5650. * Returns the final transformation matrix : world * view * projection * viewport
  5651. */
  5652. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5653. var cw = viewport.width;
  5654. var ch = viewport.height;
  5655. var cx = viewport.x;
  5656. var cy = viewport.y;
  5657. 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);
  5658. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5659. };
  5660. /**
  5661. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5662. */
  5663. Matrix.GetAsMatrix2x2 = function (matrix) {
  5664. return new Float32Array([
  5665. matrix.m[0], matrix.m[1],
  5666. matrix.m[4], matrix.m[5]
  5667. ]);
  5668. };
  5669. /**
  5670. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5671. */
  5672. Matrix.GetAsMatrix3x3 = function (matrix) {
  5673. return new Float32Array([
  5674. matrix.m[0], matrix.m[1], matrix.m[2],
  5675. matrix.m[4], matrix.m[5], matrix.m[6],
  5676. matrix.m[8], matrix.m[9], matrix.m[10]
  5677. ]);
  5678. };
  5679. /**
  5680. * Compute the transpose of the passed Matrix.
  5681. * Returns a new Matrix.
  5682. */
  5683. Matrix.Transpose = function (matrix) {
  5684. var result = new Matrix();
  5685. Matrix.TransposeToRef(matrix, result);
  5686. return result;
  5687. };
  5688. /**
  5689. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5690. */
  5691. Matrix.TransposeToRef = function (matrix, result) {
  5692. result.m[0] = matrix.m[0];
  5693. result.m[1] = matrix.m[4];
  5694. result.m[2] = matrix.m[8];
  5695. result.m[3] = matrix.m[12];
  5696. result.m[4] = matrix.m[1];
  5697. result.m[5] = matrix.m[5];
  5698. result.m[6] = matrix.m[9];
  5699. result.m[7] = matrix.m[13];
  5700. result.m[8] = matrix.m[2];
  5701. result.m[9] = matrix.m[6];
  5702. result.m[10] = matrix.m[10];
  5703. result.m[11] = matrix.m[14];
  5704. result.m[12] = matrix.m[3];
  5705. result.m[13] = matrix.m[7];
  5706. result.m[14] = matrix.m[11];
  5707. result.m[15] = matrix.m[15];
  5708. };
  5709. /**
  5710. * Returns a new Matrix as the reflection matrix across the passed plane.
  5711. */
  5712. Matrix.Reflection = function (plane) {
  5713. var matrix = new Matrix();
  5714. Matrix.ReflectionToRef(plane, matrix);
  5715. return matrix;
  5716. };
  5717. /**
  5718. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5719. */
  5720. Matrix.ReflectionToRef = function (plane, result) {
  5721. plane.normalize();
  5722. var x = plane.normal.x;
  5723. var y = plane.normal.y;
  5724. var z = plane.normal.z;
  5725. var temp = -2 * x;
  5726. var temp2 = -2 * y;
  5727. var temp3 = -2 * z;
  5728. result.m[0] = (temp * x) + 1;
  5729. result.m[1] = temp2 * x;
  5730. result.m[2] = temp3 * x;
  5731. result.m[3] = 0.0;
  5732. result.m[4] = temp * y;
  5733. result.m[5] = (temp2 * y) + 1;
  5734. result.m[6] = temp3 * y;
  5735. result.m[7] = 0.0;
  5736. result.m[8] = temp * z;
  5737. result.m[9] = temp2 * z;
  5738. result.m[10] = (temp3 * z) + 1;
  5739. result.m[11] = 0.0;
  5740. result.m[12] = temp * plane.d;
  5741. result.m[13] = temp2 * plane.d;
  5742. result.m[14] = temp3 * plane.d;
  5743. result.m[15] = 1.0;
  5744. result._markAsUpdated();
  5745. };
  5746. /**
  5747. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5748. */
  5749. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5750. result.m[0] = xaxis.x;
  5751. result.m[1] = xaxis.y;
  5752. result.m[2] = xaxis.z;
  5753. result.m[3] = 0.0;
  5754. result.m[4] = yaxis.x;
  5755. result.m[5] = yaxis.y;
  5756. result.m[6] = yaxis.z;
  5757. result.m[7] = 0.0;
  5758. result.m[8] = zaxis.x;
  5759. result.m[9] = zaxis.y;
  5760. result.m[10] = zaxis.z;
  5761. result.m[11] = 0.0;
  5762. result.m[12] = 0.0;
  5763. result.m[13] = 0.0;
  5764. result.m[14] = 0.0;
  5765. result.m[15] = 1.0;
  5766. result._markAsUpdated();
  5767. };
  5768. /**
  5769. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5770. */
  5771. Matrix.FromQuaternionToRef = function (quat, result) {
  5772. var xx = quat.x * quat.x;
  5773. var yy = quat.y * quat.y;
  5774. var zz = quat.z * quat.z;
  5775. var xy = quat.x * quat.y;
  5776. var zw = quat.z * quat.w;
  5777. var zx = quat.z * quat.x;
  5778. var yw = quat.y * quat.w;
  5779. var yz = quat.y * quat.z;
  5780. var xw = quat.x * quat.w;
  5781. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5782. result.m[1] = 2.0 * (xy + zw);
  5783. result.m[2] = 2.0 * (zx - yw);
  5784. result.m[3] = 0.0;
  5785. result.m[4] = 2.0 * (xy - zw);
  5786. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5787. result.m[6] = 2.0 * (yz + xw);
  5788. result.m[7] = 0.0;
  5789. result.m[8] = 2.0 * (zx + yw);
  5790. result.m[9] = 2.0 * (yz - xw);
  5791. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5792. result.m[11] = 0.0;
  5793. result.m[12] = 0.0;
  5794. result.m[13] = 0.0;
  5795. result.m[14] = 0.0;
  5796. result.m[15] = 1.0;
  5797. result._markAsUpdated();
  5798. };
  5799. Matrix._tempQuaternion = new Quaternion();
  5800. Matrix._xAxis = Vector3.Zero();
  5801. Matrix._yAxis = Vector3.Zero();
  5802. Matrix._zAxis = Vector3.Zero();
  5803. Matrix._updateFlagSeed = 0;
  5804. Matrix._identityReadOnly = Matrix.Identity();
  5805. return Matrix;
  5806. }());
  5807. BABYLON.Matrix = Matrix;
  5808. var Plane = /** @class */ (function () {
  5809. /**
  5810. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5811. */
  5812. function Plane(a, b, c, d) {
  5813. this.normal = new Vector3(a, b, c);
  5814. this.d = d;
  5815. }
  5816. /**
  5817. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5818. */
  5819. Plane.prototype.asArray = function () {
  5820. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5821. };
  5822. // Methods
  5823. /**
  5824. * Returns a new plane copied from the current Plane.
  5825. */
  5826. Plane.prototype.clone = function () {
  5827. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5828. };
  5829. /**
  5830. * Returns the string "Plane".
  5831. */
  5832. Plane.prototype.getClassName = function () {
  5833. return "Plane";
  5834. };
  5835. /**
  5836. * Returns the Plane hash code.
  5837. */
  5838. Plane.prototype.getHashCode = function () {
  5839. var hash = this.normal.getHashCode();
  5840. hash = (hash * 397) ^ (this.d || 0);
  5841. return hash;
  5842. };
  5843. /**
  5844. * Normalize the current Plane in place.
  5845. * Returns the updated Plane.
  5846. */
  5847. Plane.prototype.normalize = function () {
  5848. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5849. var magnitude = 0.0;
  5850. if (norm !== 0) {
  5851. magnitude = 1.0 / norm;
  5852. }
  5853. this.normal.x *= magnitude;
  5854. this.normal.y *= magnitude;
  5855. this.normal.z *= magnitude;
  5856. this.d *= magnitude;
  5857. return this;
  5858. };
  5859. /**
  5860. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5861. */
  5862. Plane.prototype.transform = function (transformation) {
  5863. var transposedMatrix = Matrix.Transpose(transformation);
  5864. var x = this.normal.x;
  5865. var y = this.normal.y;
  5866. var z = this.normal.z;
  5867. var d = this.d;
  5868. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5869. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5870. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5871. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5872. return new Plane(normalX, normalY, normalZ, finalD);
  5873. };
  5874. /**
  5875. * Returns the dot product (float) of the point coordinates and the plane normal.
  5876. */
  5877. Plane.prototype.dotCoordinate = function (point) {
  5878. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5879. };
  5880. /**
  5881. * Updates the current Plane from the plane defined by the three passed points.
  5882. * Returns the updated Plane.
  5883. */
  5884. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5885. var x1 = point2.x - point1.x;
  5886. var y1 = point2.y - point1.y;
  5887. var z1 = point2.z - point1.z;
  5888. var x2 = point3.x - point1.x;
  5889. var y2 = point3.y - point1.y;
  5890. var z2 = point3.z - point1.z;
  5891. var yz = (y1 * z2) - (z1 * y2);
  5892. var xz = (z1 * x2) - (x1 * z2);
  5893. var xy = (x1 * y2) - (y1 * x2);
  5894. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5895. var invPyth;
  5896. if (pyth !== 0) {
  5897. invPyth = 1.0 / pyth;
  5898. }
  5899. else {
  5900. invPyth = 0.0;
  5901. }
  5902. this.normal.x = yz * invPyth;
  5903. this.normal.y = xz * invPyth;
  5904. this.normal.z = xy * invPyth;
  5905. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5906. return this;
  5907. };
  5908. /**
  5909. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5910. */
  5911. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5912. var dot = Vector3.Dot(this.normal, direction);
  5913. return (dot <= epsilon);
  5914. };
  5915. /**
  5916. * Returns the signed distance (float) from the passed point to the Plane.
  5917. */
  5918. Plane.prototype.signedDistanceTo = function (point) {
  5919. return Vector3.Dot(point, this.normal) + this.d;
  5920. };
  5921. // Statics
  5922. /**
  5923. * Returns a new Plane from the passed array.
  5924. */
  5925. Plane.FromArray = function (array) {
  5926. return new Plane(array[0], array[1], array[2], array[3]);
  5927. };
  5928. /**
  5929. * Returns a new Plane defined by the three passed points.
  5930. */
  5931. Plane.FromPoints = function (point1, point2, point3) {
  5932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5933. result.copyFromPoints(point1, point2, point3);
  5934. return result;
  5935. };
  5936. /**
  5937. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5938. * Note : the vector "normal" is updated because normalized.
  5939. */
  5940. Plane.FromPositionAndNormal = function (origin, normal) {
  5941. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5942. normal.normalize();
  5943. result.normal = normal;
  5944. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5945. return result;
  5946. };
  5947. /**
  5948. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5949. */
  5950. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5951. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5952. return Vector3.Dot(point, normal) + d;
  5953. };
  5954. return Plane;
  5955. }());
  5956. BABYLON.Plane = Plane;
  5957. var Viewport = /** @class */ (function () {
  5958. /**
  5959. * Creates a Viewport object located at (x, y) and sized (width, height).
  5960. */
  5961. function Viewport(x, y, width, height) {
  5962. this.x = x;
  5963. this.y = y;
  5964. this.width = width;
  5965. this.height = height;
  5966. }
  5967. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5968. if (renderWidthOrEngine.getRenderWidth) {
  5969. var engine = renderWidthOrEngine;
  5970. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5971. }
  5972. var renderWidth = renderWidthOrEngine;
  5973. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5974. };
  5975. /**
  5976. * Returns a new Viewport copied from the current one.
  5977. */
  5978. Viewport.prototype.clone = function () {
  5979. return new Viewport(this.x, this.y, this.width, this.height);
  5980. };
  5981. return Viewport;
  5982. }());
  5983. BABYLON.Viewport = Viewport;
  5984. var Frustum = /** @class */ (function () {
  5985. function Frustum() {
  5986. }
  5987. /**
  5988. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5989. */
  5990. Frustum.GetPlanes = function (transform) {
  5991. var frustumPlanes = [];
  5992. for (var index = 0; index < 6; index++) {
  5993. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5994. }
  5995. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5996. return frustumPlanes;
  5997. };
  5998. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5999. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6000. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6001. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6002. frustumPlane.d = transform.m[15] + transform.m[14];
  6003. frustumPlane.normalize();
  6004. };
  6005. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6006. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6007. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6008. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6009. frustumPlane.d = transform.m[15] - transform.m[14];
  6010. frustumPlane.normalize();
  6011. };
  6012. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6013. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6014. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6015. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6016. frustumPlane.d = transform.m[15] + transform.m[12];
  6017. frustumPlane.normalize();
  6018. };
  6019. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6020. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6021. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6022. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6023. frustumPlane.d = transform.m[15] - transform.m[12];
  6024. frustumPlane.normalize();
  6025. };
  6026. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6027. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6028. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6029. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6030. frustumPlane.d = transform.m[15] - transform.m[13];
  6031. frustumPlane.normalize();
  6032. };
  6033. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6034. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6035. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6036. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6037. frustumPlane.d = transform.m[15] + transform.m[13];
  6038. frustumPlane.normalize();
  6039. };
  6040. /**
  6041. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6042. */
  6043. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6044. // Near
  6045. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6046. // Far
  6047. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6048. // Left
  6049. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6050. // Right
  6051. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6052. // Top
  6053. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6054. // Bottom
  6055. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6056. };
  6057. return Frustum;
  6058. }());
  6059. BABYLON.Frustum = Frustum;
  6060. var Space;
  6061. (function (Space) {
  6062. Space[Space["LOCAL"] = 0] = "LOCAL";
  6063. Space[Space["WORLD"] = 1] = "WORLD";
  6064. Space[Space["BONE"] = 2] = "BONE";
  6065. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6066. var Axis = /** @class */ (function () {
  6067. function Axis() {
  6068. }
  6069. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6070. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6071. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6072. return Axis;
  6073. }());
  6074. BABYLON.Axis = Axis;
  6075. ;
  6076. var BezierCurve = /** @class */ (function () {
  6077. function BezierCurve() {
  6078. }
  6079. /**
  6080. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6081. */
  6082. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6083. // Extract X (which is equal to time here)
  6084. var f0 = 1 - 3 * x2 + 3 * x1;
  6085. var f1 = 3 * x2 - 6 * x1;
  6086. var f2 = 3 * x1;
  6087. var refinedT = t;
  6088. for (var i = 0; i < 5; i++) {
  6089. var refinedT2 = refinedT * refinedT;
  6090. var refinedT3 = refinedT2 * refinedT;
  6091. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6092. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6093. refinedT -= (x - t) * slope;
  6094. refinedT = Math.min(1, Math.max(0, refinedT));
  6095. }
  6096. // Resolve cubic bezier for the given x
  6097. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6098. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6099. Math.pow(refinedT, 3);
  6100. };
  6101. return BezierCurve;
  6102. }());
  6103. BABYLON.BezierCurve = BezierCurve;
  6104. var Orientation;
  6105. (function (Orientation) {
  6106. Orientation[Orientation["CW"] = 0] = "CW";
  6107. Orientation[Orientation["CCW"] = 1] = "CCW";
  6108. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6109. var Angle = /** @class */ (function () {
  6110. /**
  6111. * Creates an Angle object of "radians" radians (float).
  6112. */
  6113. function Angle(radians) {
  6114. var _this = this;
  6115. /**
  6116. * Returns the Angle value in degrees (float).
  6117. */
  6118. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6119. /**
  6120. * Returns the Angle value in radians (float).
  6121. */
  6122. this.radians = function () { return _this._radians; };
  6123. this._radians = radians;
  6124. if (this._radians < 0.0)
  6125. this._radians += (2.0 * Math.PI);
  6126. }
  6127. /**
  6128. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6129. */
  6130. Angle.BetweenTwoPoints = function (a, b) {
  6131. var delta = b.subtract(a);
  6132. var theta = Math.atan2(delta.y, delta.x);
  6133. return new Angle(theta);
  6134. };
  6135. /**
  6136. * Returns a new Angle object from the passed float in radians.
  6137. */
  6138. Angle.FromRadians = function (radians) {
  6139. return new Angle(radians);
  6140. };
  6141. /**
  6142. * Returns a new Angle object from the passed float in degrees.
  6143. */
  6144. Angle.FromDegrees = function (degrees) {
  6145. return new Angle(degrees * Math.PI / 180.0);
  6146. };
  6147. return Angle;
  6148. }());
  6149. BABYLON.Angle = Angle;
  6150. var Arc2 = /** @class */ (function () {
  6151. /**
  6152. * Creates an Arc object from the three passed points : start, middle and end.
  6153. */
  6154. function Arc2(startPoint, midPoint, endPoint) {
  6155. this.startPoint = startPoint;
  6156. this.midPoint = midPoint;
  6157. this.endPoint = endPoint;
  6158. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6159. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6160. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6161. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6162. 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);
  6163. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6164. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6165. var a1 = this.startAngle.degrees();
  6166. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6167. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6168. // angles correction
  6169. if (a2 - a1 > +180.0)
  6170. a2 -= 360.0;
  6171. if (a2 - a1 < -180.0)
  6172. a2 += 360.0;
  6173. if (a3 - a2 > +180.0)
  6174. a3 -= 360.0;
  6175. if (a3 - a2 < -180.0)
  6176. a3 += 360.0;
  6177. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6178. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6179. }
  6180. return Arc2;
  6181. }());
  6182. BABYLON.Arc2 = Arc2;
  6183. var Path2 = /** @class */ (function () {
  6184. /**
  6185. * Creates a Path2 object from the starting 2D coordinates x and y.
  6186. */
  6187. function Path2(x, y) {
  6188. this._points = new Array();
  6189. this._length = 0.0;
  6190. this.closed = false;
  6191. this._points.push(new Vector2(x, y));
  6192. }
  6193. /**
  6194. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6195. * Returns the updated Path2.
  6196. */
  6197. Path2.prototype.addLineTo = function (x, y) {
  6198. if (this.closed) {
  6199. return this;
  6200. }
  6201. var newPoint = new Vector2(x, y);
  6202. var previousPoint = this._points[this._points.length - 1];
  6203. this._points.push(newPoint);
  6204. this._length += newPoint.subtract(previousPoint).length();
  6205. return this;
  6206. };
  6207. /**
  6208. * 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.
  6209. * Returns the updated Path2.
  6210. */
  6211. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6212. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6213. if (this.closed) {
  6214. return this;
  6215. }
  6216. var startPoint = this._points[this._points.length - 1];
  6217. var midPoint = new Vector2(midX, midY);
  6218. var endPoint = new Vector2(endX, endY);
  6219. var arc = new Arc2(startPoint, midPoint, endPoint);
  6220. var increment = arc.angle.radians() / numberOfSegments;
  6221. if (arc.orientation === Orientation.CW)
  6222. increment *= -1;
  6223. var currentAngle = arc.startAngle.radians() + increment;
  6224. for (var i = 0; i < numberOfSegments; i++) {
  6225. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6226. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6227. this.addLineTo(x, y);
  6228. currentAngle += increment;
  6229. }
  6230. return this;
  6231. };
  6232. /**
  6233. * Closes the Path2.
  6234. * Returns the Path2.
  6235. */
  6236. Path2.prototype.close = function () {
  6237. this.closed = true;
  6238. return this;
  6239. };
  6240. /**
  6241. * Returns the Path2 total length (float).
  6242. */
  6243. Path2.prototype.length = function () {
  6244. var result = this._length;
  6245. if (!this.closed) {
  6246. var lastPoint = this._points[this._points.length - 1];
  6247. var firstPoint = this._points[0];
  6248. result += (firstPoint.subtract(lastPoint).length());
  6249. }
  6250. return result;
  6251. };
  6252. /**
  6253. * Returns the Path2 internal array of points.
  6254. */
  6255. Path2.prototype.getPoints = function () {
  6256. return this._points;
  6257. };
  6258. /**
  6259. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6260. */
  6261. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6262. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6263. return Vector2.Zero();
  6264. }
  6265. var lengthPosition = normalizedLengthPosition * this.length();
  6266. var previousOffset = 0;
  6267. for (var i = 0; i < this._points.length; i++) {
  6268. var j = (i + 1) % this._points.length;
  6269. var a = this._points[i];
  6270. var b = this._points[j];
  6271. var bToA = b.subtract(a);
  6272. var nextOffset = (bToA.length() + previousOffset);
  6273. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6274. var dir = bToA.normalize();
  6275. var localOffset = lengthPosition - previousOffset;
  6276. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6277. }
  6278. previousOffset = nextOffset;
  6279. }
  6280. return Vector2.Zero();
  6281. };
  6282. /**
  6283. * Returns a new Path2 starting at the coordinates (x, y).
  6284. */
  6285. Path2.StartingAt = function (x, y) {
  6286. return new Path2(x, y);
  6287. };
  6288. return Path2;
  6289. }());
  6290. BABYLON.Path2 = Path2;
  6291. var Path3D = /** @class */ (function () {
  6292. /**
  6293. * new Path3D(path, normal, raw)
  6294. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6295. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6296. * path : an array of Vector3, the curve axis of the Path3D
  6297. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6298. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6299. */
  6300. function Path3D(path, firstNormal, raw) {
  6301. if (firstNormal === void 0) { firstNormal = null; }
  6302. this.path = path;
  6303. this._curve = new Array();
  6304. this._distances = new Array();
  6305. this._tangents = new Array();
  6306. this._normals = new Array();
  6307. this._binormals = new Array();
  6308. for (var p = 0; p < path.length; p++) {
  6309. this._curve[p] = path[p].clone(); // hard copy
  6310. }
  6311. this._raw = raw || false;
  6312. this._compute(firstNormal);
  6313. }
  6314. /**
  6315. * Returns the Path3D array of successive Vector3 designing its curve.
  6316. */
  6317. Path3D.prototype.getCurve = function () {
  6318. return this._curve;
  6319. };
  6320. /**
  6321. * Returns an array populated with tangent vectors on each Path3D curve point.
  6322. */
  6323. Path3D.prototype.getTangents = function () {
  6324. return this._tangents;
  6325. };
  6326. /**
  6327. * Returns an array populated with normal vectors on each Path3D curve point.
  6328. */
  6329. Path3D.prototype.getNormals = function () {
  6330. return this._normals;
  6331. };
  6332. /**
  6333. * Returns an array populated with binormal vectors on each Path3D curve point.
  6334. */
  6335. Path3D.prototype.getBinormals = function () {
  6336. return this._binormals;
  6337. };
  6338. /**
  6339. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6340. */
  6341. Path3D.prototype.getDistances = function () {
  6342. return this._distances;
  6343. };
  6344. /**
  6345. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6346. * Returns the same object updated.
  6347. */
  6348. Path3D.prototype.update = function (path, firstNormal) {
  6349. if (firstNormal === void 0) { firstNormal = null; }
  6350. for (var p = 0; p < path.length; p++) {
  6351. this._curve[p].x = path[p].x;
  6352. this._curve[p].y = path[p].y;
  6353. this._curve[p].z = path[p].z;
  6354. }
  6355. this._compute(firstNormal);
  6356. return this;
  6357. };
  6358. // private function compute() : computes tangents, normals and binormals
  6359. Path3D.prototype._compute = function (firstNormal) {
  6360. var l = this._curve.length;
  6361. // first and last tangents
  6362. this._tangents[0] = this._getFirstNonNullVector(0);
  6363. if (!this._raw) {
  6364. this._tangents[0].normalize();
  6365. }
  6366. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6367. if (!this._raw) {
  6368. this._tangents[l - 1].normalize();
  6369. }
  6370. // normals and binormals at first point : arbitrary vector with _normalVector()
  6371. var tg0 = this._tangents[0];
  6372. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6373. this._normals[0] = pp0;
  6374. if (!this._raw) {
  6375. this._normals[0].normalize();
  6376. }
  6377. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6378. if (!this._raw) {
  6379. this._binormals[0].normalize();
  6380. }
  6381. this._distances[0] = 0.0;
  6382. // normals and binormals : next points
  6383. var prev; // previous vector (segment)
  6384. var cur; // current vector (segment)
  6385. var curTang; // current tangent
  6386. // previous normal
  6387. var prevBinor; // previous binormal
  6388. for (var i = 1; i < l; i++) {
  6389. // tangents
  6390. prev = this._getLastNonNullVector(i);
  6391. if (i < l - 1) {
  6392. cur = this._getFirstNonNullVector(i);
  6393. this._tangents[i] = prev.add(cur);
  6394. this._tangents[i].normalize();
  6395. }
  6396. this._distances[i] = this._distances[i - 1] + prev.length();
  6397. // normals and binormals
  6398. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6399. curTang = this._tangents[i];
  6400. prevBinor = this._binormals[i - 1];
  6401. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6402. if (!this._raw) {
  6403. this._normals[i].normalize();
  6404. }
  6405. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6406. if (!this._raw) {
  6407. this._binormals[i].normalize();
  6408. }
  6409. }
  6410. };
  6411. // private function getFirstNonNullVector(index)
  6412. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6413. Path3D.prototype._getFirstNonNullVector = function (index) {
  6414. var i = 1;
  6415. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6416. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6417. i++;
  6418. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6419. }
  6420. return nNVector;
  6421. };
  6422. // private function getLastNonNullVector(index)
  6423. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6424. Path3D.prototype._getLastNonNullVector = function (index) {
  6425. var i = 1;
  6426. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6427. while (nLVector.length() === 0 && index > i + 1) {
  6428. i++;
  6429. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6430. }
  6431. return nLVector;
  6432. };
  6433. // private function normalVector(v0, vt, va) :
  6434. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6435. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6436. Path3D.prototype._normalVector = function (v0, vt, va) {
  6437. var normal0;
  6438. var tgl = vt.length();
  6439. if (tgl === 0.0) {
  6440. tgl = 1.0;
  6441. }
  6442. if (va === undefined || va === null) {
  6443. var point;
  6444. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6445. point = new Vector3(0.0, -1.0, 0.0);
  6446. }
  6447. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6448. point = new Vector3(1.0, 0.0, 0.0);
  6449. }
  6450. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6451. point = new Vector3(0.0, 0.0, 1.0);
  6452. }
  6453. else {
  6454. point = Vector3.Zero();
  6455. }
  6456. normal0 = Vector3.Cross(vt, point);
  6457. }
  6458. else {
  6459. normal0 = Vector3.Cross(vt, va);
  6460. Vector3.CrossToRef(normal0, vt, normal0);
  6461. }
  6462. normal0.normalize();
  6463. return normal0;
  6464. };
  6465. return Path3D;
  6466. }());
  6467. BABYLON.Path3D = Path3D;
  6468. var Curve3 = /** @class */ (function () {
  6469. /**
  6470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6471. * A Curve3 is designed from a series of successive Vector3.
  6472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6473. */
  6474. function Curve3(points) {
  6475. this._length = 0.0;
  6476. this._points = points;
  6477. this._length = this._computeLength(points);
  6478. }
  6479. /**
  6480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6482. * @param v1 (Vector3) the control point
  6483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6484. * @param nbPoints (integer) the wanted number of points in the curve
  6485. */
  6486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6488. var bez = new Array();
  6489. var equation = function (t, val0, val1, val2) {
  6490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6491. return res;
  6492. };
  6493. for (var i = 0; i <= nbPoints; i++) {
  6494. 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)));
  6495. }
  6496. return new Curve3(bez);
  6497. };
  6498. /**
  6499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6501. * @param v1 (Vector3) the first control point
  6502. * @param v2 (Vector3) the second control point
  6503. * @param v3 (Vector3) the end point of the Cubic Bezier
  6504. * @param nbPoints (integer) the wanted number of points in the curve
  6505. */
  6506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6508. var bez = new Array();
  6509. var equation = function (t, val0, val1, val2, val3) {
  6510. 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;
  6511. return res;
  6512. };
  6513. for (var i = 0; i <= nbPoints; i++) {
  6514. 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)));
  6515. }
  6516. return new Curve3(bez);
  6517. };
  6518. /**
  6519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6520. * @param p1 (Vector3) the origin point of the Hermite Spline
  6521. * @param t1 (Vector3) the tangent vector at the origin point
  6522. * @param p2 (Vector3) the end point of the Hermite Spline
  6523. * @param t2 (Vector3) the tangent vector at the end point
  6524. * @param nbPoints (integer) the wanted number of points in the curve
  6525. */
  6526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6527. var hermite = new Array();
  6528. var step = 1.0 / nbPoints;
  6529. for (var i = 0; i <= nbPoints; i++) {
  6530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6531. }
  6532. return new Curve3(hermite);
  6533. };
  6534. /**
  6535. * Returns a Curve3 object along a CatmullRom Spline curve :
  6536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6538. */
  6539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6540. var totalPoints = new Array();
  6541. totalPoints.push(points[0].clone());
  6542. Array.prototype.push.apply(totalPoints, points);
  6543. totalPoints.push(points[points.length - 1].clone());
  6544. var catmullRom = new Array();
  6545. var step = 1.0 / nbPoints;
  6546. var amount = 0.0;
  6547. for (var i = 0; i < totalPoints.length - 3; i++) {
  6548. amount = 0;
  6549. for (var c = 0; c < nbPoints; c++) {
  6550. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6551. amount += step;
  6552. }
  6553. }
  6554. i--;
  6555. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6556. return new Curve3(catmullRom);
  6557. };
  6558. /**
  6559. * Returns the Curve3 stored array of successive Vector3
  6560. */
  6561. Curve3.prototype.getPoints = function () {
  6562. return this._points;
  6563. };
  6564. /**
  6565. * Returns the computed length (float) of the curve.
  6566. */
  6567. Curve3.prototype.length = function () {
  6568. return this._length;
  6569. };
  6570. /**
  6571. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6572. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6573. * curveA and curveB keep unchanged.
  6574. */
  6575. Curve3.prototype.continue = function (curve) {
  6576. var lastPoint = this._points[this._points.length - 1];
  6577. var continuedPoints = this._points.slice();
  6578. var curvePoints = curve.getPoints();
  6579. for (var i = 1; i < curvePoints.length; i++) {
  6580. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6581. }
  6582. var continuedCurve = new Curve3(continuedPoints);
  6583. return continuedCurve;
  6584. };
  6585. Curve3.prototype._computeLength = function (path) {
  6586. var l = 0;
  6587. for (var i = 1; i < path.length; i++) {
  6588. l += (path[i].subtract(path[i - 1])).length();
  6589. }
  6590. return l;
  6591. };
  6592. return Curve3;
  6593. }());
  6594. BABYLON.Curve3 = Curve3;
  6595. // Vertex formats
  6596. var PositionNormalVertex = /** @class */ (function () {
  6597. function PositionNormalVertex(position, normal) {
  6598. if (position === void 0) { position = Vector3.Zero(); }
  6599. if (normal === void 0) { normal = Vector3.Up(); }
  6600. this.position = position;
  6601. this.normal = normal;
  6602. }
  6603. PositionNormalVertex.prototype.clone = function () {
  6604. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6605. };
  6606. return PositionNormalVertex;
  6607. }());
  6608. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6609. var PositionNormalTextureVertex = /** @class */ (function () {
  6610. function PositionNormalTextureVertex(position, normal, uv) {
  6611. if (position === void 0) { position = Vector3.Zero(); }
  6612. if (normal === void 0) { normal = Vector3.Up(); }
  6613. if (uv === void 0) { uv = Vector2.Zero(); }
  6614. this.position = position;
  6615. this.normal = normal;
  6616. this.uv = uv;
  6617. }
  6618. PositionNormalTextureVertex.prototype.clone = function () {
  6619. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6620. };
  6621. return PositionNormalTextureVertex;
  6622. }());
  6623. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6624. // Temporary pre-allocated objects for engine internal use
  6625. // usage in any internal function :
  6626. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6627. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6628. var Tmp = /** @class */ (function () {
  6629. function Tmp() {
  6630. }
  6631. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6632. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6633. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6634. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6635. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6636. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6637. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6638. Matrix.Zero(), Matrix.Zero(),
  6639. Matrix.Zero(), Matrix.Zero(),
  6640. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6641. return Tmp;
  6642. }());
  6643. BABYLON.Tmp = Tmp;
  6644. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6645. var MathTmp = /** @class */ (function () {
  6646. function MathTmp() {
  6647. }
  6648. MathTmp.Vector3 = [Vector3.Zero()];
  6649. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6650. MathTmp.Quaternion = [Quaternion.Zero()];
  6651. return MathTmp;
  6652. }());
  6653. })(BABYLON || (BABYLON = {}));
  6654. //# sourceMappingURL=babylon.math.js.map
  6655. var BABYLON;
  6656. (function (BABYLON) {
  6657. var Scalar = /** @class */ (function () {
  6658. function Scalar() {
  6659. }
  6660. /**
  6661. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6662. */
  6663. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6664. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6665. var num = a - b;
  6666. return -epsilon <= num && num <= epsilon;
  6667. };
  6668. /**
  6669. * Returns a string : the upper case translation of the number i to hexadecimal.
  6670. */
  6671. Scalar.ToHex = function (i) {
  6672. var str = i.toString(16);
  6673. if (i <= 15) {
  6674. return ("0" + str).toUpperCase();
  6675. }
  6676. return str.toUpperCase();
  6677. };
  6678. /**
  6679. * Returns -1 if value is negative and +1 is value is positive.
  6680. * Returns the value itself if it's equal to zero.
  6681. */
  6682. Scalar.Sign = function (value) {
  6683. value = +value; // convert to a number
  6684. if (value === 0 || isNaN(value))
  6685. return value;
  6686. return value > 0 ? 1 : -1;
  6687. };
  6688. /**
  6689. * Returns the value itself if it's between min and max.
  6690. * Returns min if the value is lower than min.
  6691. * Returns max if the value is greater than max.
  6692. */
  6693. Scalar.Clamp = function (value, min, max) {
  6694. if (min === void 0) { min = 0; }
  6695. if (max === void 0) { max = 1; }
  6696. return Math.min(max, Math.max(min, value));
  6697. };
  6698. /**
  6699. * Returns the log2 of value.
  6700. */
  6701. Scalar.Log2 = function (value) {
  6702. return Math.log(value) * Math.LOG2E;
  6703. };
  6704. /**
  6705. * Loops the value, so that it is never larger than length and never smaller than 0.
  6706. *
  6707. * This is similar to the modulo operator but it works with floating point numbers.
  6708. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6709. * With t = 5 and length = 2.5, the result would be 0.0.
  6710. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6711. */
  6712. Scalar.Repeat = function (value, length) {
  6713. return value - Math.floor(value / length) * length;
  6714. };
  6715. /**
  6716. * Normalize the value between 0.0 and 1.0 using min and max values
  6717. */
  6718. Scalar.Normalize = function (value, min, max) {
  6719. return (value - min) / (max - min);
  6720. };
  6721. /**
  6722. * Denormalize the value from 0.0 and 1.0 using min and max values
  6723. */
  6724. Scalar.Denormalize = function (normalized, min, max) {
  6725. return (normalized * (max - min) + min);
  6726. };
  6727. /**
  6728. * Calculates the shortest difference between two given angles given in degrees.
  6729. */
  6730. Scalar.DeltaAngle = function (current, target) {
  6731. var num = Scalar.Repeat(target - current, 360.0);
  6732. if (num > 180.0) {
  6733. num -= 360.0;
  6734. }
  6735. return num;
  6736. };
  6737. /**
  6738. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6739. *
  6740. * The returned value will move back and forth between 0 and length
  6741. */
  6742. Scalar.PingPong = function (tx, length) {
  6743. var t = Scalar.Repeat(tx, length * 2.0);
  6744. return length - Math.abs(t - length);
  6745. };
  6746. /**
  6747. * Interpolates between min and max with smoothing at the limits.
  6748. *
  6749. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6750. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6751. */
  6752. Scalar.SmoothStep = function (from, to, tx) {
  6753. var t = Scalar.Clamp(tx);
  6754. t = -2.0 * t * t * t + 3.0 * t * t;
  6755. return to * t + from * (1.0 - t);
  6756. };
  6757. /**
  6758. * Moves a value current towards target.
  6759. *
  6760. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6761. * Negative values of maxDelta pushes the value away from target.
  6762. */
  6763. Scalar.MoveTowards = function (current, target, maxDelta) {
  6764. var result = 0;
  6765. if (Math.abs(target - current) <= maxDelta) {
  6766. result = target;
  6767. }
  6768. else {
  6769. result = current + Scalar.Sign(target - current) * maxDelta;
  6770. }
  6771. return result;
  6772. };
  6773. /**
  6774. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6775. *
  6776. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6777. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6778. */
  6779. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6780. var num = Scalar.DeltaAngle(current, target);
  6781. var result = 0;
  6782. if (-maxDelta < num && num < maxDelta) {
  6783. result = target;
  6784. }
  6785. else {
  6786. target = current + num;
  6787. result = Scalar.MoveTowards(current, target, maxDelta);
  6788. }
  6789. return result;
  6790. };
  6791. /**
  6792. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6793. */
  6794. Scalar.Lerp = function (start, end, amount) {
  6795. return start + ((end - start) * amount);
  6796. };
  6797. /**
  6798. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6799. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6800. */
  6801. Scalar.LerpAngle = function (start, end, amount) {
  6802. var num = Scalar.Repeat(end - start, 360.0);
  6803. if (num > 180.0) {
  6804. num -= 360.0;
  6805. }
  6806. return start + num * Scalar.Clamp(amount);
  6807. };
  6808. /**
  6809. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6810. */
  6811. Scalar.InverseLerp = function (a, b, value) {
  6812. var result = 0;
  6813. if (a != b) {
  6814. result = Scalar.Clamp((value - a) / (b - a));
  6815. }
  6816. else {
  6817. result = 0.0;
  6818. }
  6819. return result;
  6820. };
  6821. /**
  6822. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6823. */
  6824. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6825. var squared = amount * amount;
  6826. var cubed = amount * squared;
  6827. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6828. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6829. var part3 = (cubed - (2.0 * squared)) + amount;
  6830. var part4 = cubed - squared;
  6831. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6832. };
  6833. /**
  6834. * Returns a random float number between and min and max values
  6835. */
  6836. Scalar.RandomRange = function (min, max) {
  6837. if (min === max)
  6838. return min;
  6839. return ((Math.random() * (max - min)) + min);
  6840. };
  6841. /**
  6842. * This function returns percentage of a number in a given range.
  6843. *
  6844. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6845. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6846. */
  6847. Scalar.RangeToPercent = function (number, min, max) {
  6848. return ((number - min) / (max - min));
  6849. };
  6850. /**
  6851. * This function returns number that corresponds to the percentage in a given range.
  6852. *
  6853. * PercentToRange(0.34,0,100) will return 34.
  6854. */
  6855. Scalar.PercentToRange = function (percent, min, max) {
  6856. return ((max - min) * percent + min);
  6857. };
  6858. /**
  6859. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6860. * @param angle The angle to normalize in radian.
  6861. * @return The converted angle.
  6862. */
  6863. Scalar.NormalizeRadians = function (angle) {
  6864. // More precise but slower version kept for reference.
  6865. // angle = angle % Tools.TwoPi;
  6866. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6867. //if (angle > Math.PI) {
  6868. // angle -= Tools.TwoPi;
  6869. //}
  6870. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6871. return angle;
  6872. };
  6873. /**
  6874. * Two pi constants convenient for computation.
  6875. */
  6876. Scalar.TwoPi = Math.PI * 2;
  6877. return Scalar;
  6878. }());
  6879. BABYLON.Scalar = Scalar;
  6880. })(BABYLON || (BABYLON = {}));
  6881. //# sourceMappingURL=babylon.math.scalar.js.map
  6882. //# sourceMappingURL=babylon.mixins.js.map
  6883. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6884. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6885. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6886. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6887. //# sourceMappingURL=babylon.webgl2.js.map
  6888. var BABYLON;
  6889. (function (BABYLON) {
  6890. var __decoratorInitialStore = {};
  6891. var __mergedStore = {};
  6892. var _copySource = function (creationFunction, source, instanciate) {
  6893. var destination = creationFunction();
  6894. // Tags
  6895. if (BABYLON.Tags) {
  6896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6897. }
  6898. var classStore = getMergedStore(destination);
  6899. // Properties
  6900. for (var property in classStore) {
  6901. var propertyDescriptor = classStore[property];
  6902. var sourceProperty = source[property];
  6903. var propertyType = propertyDescriptor.type;
  6904. if (sourceProperty !== undefined && sourceProperty !== null) {
  6905. switch (propertyType) {
  6906. case 0: // Value
  6907. case 6:// Mesh reference
  6908. destination[property] = sourceProperty;
  6909. break;
  6910. case 1:// Texture
  6911. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6912. break;
  6913. case 2: // Color3
  6914. case 3: // FresnelParameters
  6915. case 4: // Vector2
  6916. case 5: // Vector3
  6917. case 7: // Color Curves
  6918. case 10:// Quaternion
  6919. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6920. break;
  6921. }
  6922. }
  6923. }
  6924. return destination;
  6925. };
  6926. function getDirectStore(target) {
  6927. var classKey = target.getClassName();
  6928. if (!__decoratorInitialStore[classKey]) {
  6929. __decoratorInitialStore[classKey] = {};
  6930. }
  6931. return __decoratorInitialStore[classKey];
  6932. }
  6933. /**
  6934. * Return the list of properties flagged as serializable
  6935. * @param target: host object
  6936. */
  6937. function getMergedStore(target) {
  6938. var classKey = target.getClassName();
  6939. if (__mergedStore[classKey]) {
  6940. return __mergedStore[classKey];
  6941. }
  6942. __mergedStore[classKey] = {};
  6943. var store = __mergedStore[classKey];
  6944. var currentTarget = target;
  6945. var currentKey = classKey;
  6946. while (currentKey) {
  6947. var initialStore = __decoratorInitialStore[currentKey];
  6948. for (var property in initialStore) {
  6949. store[property] = initialStore[property];
  6950. }
  6951. var parent_1 = void 0;
  6952. var done = false;
  6953. do {
  6954. parent_1 = Object.getPrototypeOf(currentTarget);
  6955. if (!parent_1.getClassName) {
  6956. done = true;
  6957. break;
  6958. }
  6959. if (parent_1.getClassName() !== currentKey) {
  6960. break;
  6961. }
  6962. currentTarget = parent_1;
  6963. } while (parent_1);
  6964. if (done) {
  6965. break;
  6966. }
  6967. currentKey = parent_1.getClassName();
  6968. currentTarget = parent_1;
  6969. }
  6970. return store;
  6971. }
  6972. function generateSerializableMember(type, sourceName) {
  6973. return function (target, propertyKey) {
  6974. var classStore = getDirectStore(target);
  6975. if (!classStore[propertyKey]) {
  6976. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6977. }
  6978. };
  6979. }
  6980. function generateExpandMember(setCallback, targetKey) {
  6981. if (targetKey === void 0) { targetKey = null; }
  6982. return function (target, propertyKey) {
  6983. var key = targetKey || ("_" + propertyKey);
  6984. Object.defineProperty(target, propertyKey, {
  6985. get: function () {
  6986. return this[key];
  6987. },
  6988. set: function (value) {
  6989. if (this[key] === value) {
  6990. return;
  6991. }
  6992. this[key] = value;
  6993. target[setCallback].apply(this);
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. };
  6999. }
  7000. function expandToProperty(callback, targetKey) {
  7001. if (targetKey === void 0) { targetKey = null; }
  7002. return generateExpandMember(callback, targetKey);
  7003. }
  7004. BABYLON.expandToProperty = expandToProperty;
  7005. function serialize(sourceName) {
  7006. return generateSerializableMember(0, sourceName); // value member
  7007. }
  7008. BABYLON.serialize = serialize;
  7009. function serializeAsTexture(sourceName) {
  7010. return generateSerializableMember(1, sourceName); // texture member
  7011. }
  7012. BABYLON.serializeAsTexture = serializeAsTexture;
  7013. function serializeAsColor3(sourceName) {
  7014. return generateSerializableMember(2, sourceName); // color3 member
  7015. }
  7016. BABYLON.serializeAsColor3 = serializeAsColor3;
  7017. function serializeAsFresnelParameters(sourceName) {
  7018. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7019. }
  7020. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7021. function serializeAsVector2(sourceName) {
  7022. return generateSerializableMember(4, sourceName); // vector2 member
  7023. }
  7024. BABYLON.serializeAsVector2 = serializeAsVector2;
  7025. function serializeAsVector3(sourceName) {
  7026. return generateSerializableMember(5, sourceName); // vector3 member
  7027. }
  7028. BABYLON.serializeAsVector3 = serializeAsVector3;
  7029. function serializeAsMeshReference(sourceName) {
  7030. return generateSerializableMember(6, sourceName); // mesh reference member
  7031. }
  7032. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7033. function serializeAsColorCurves(sourceName) {
  7034. return generateSerializableMember(7, sourceName); // color curves
  7035. }
  7036. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7037. function serializeAsColor4(sourceName) {
  7038. return generateSerializableMember(8, sourceName); // color 4
  7039. }
  7040. BABYLON.serializeAsColor4 = serializeAsColor4;
  7041. function serializeAsImageProcessingConfiguration(sourceName) {
  7042. return generateSerializableMember(9, sourceName); // image processing
  7043. }
  7044. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7045. function serializeAsQuaternion(sourceName) {
  7046. return generateSerializableMember(10, sourceName); // quaternion member
  7047. }
  7048. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7049. var SerializationHelper = /** @class */ (function () {
  7050. function SerializationHelper() {
  7051. }
  7052. SerializationHelper.Serialize = function (entity, serializationObject) {
  7053. if (!serializationObject) {
  7054. serializationObject = {};
  7055. }
  7056. // Tags
  7057. if (BABYLON.Tags) {
  7058. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7059. }
  7060. var serializedProperties = getMergedStore(entity);
  7061. // Properties
  7062. for (var property in serializedProperties) {
  7063. var propertyDescriptor = serializedProperties[property];
  7064. var targetPropertyName = propertyDescriptor.sourceName || property;
  7065. var propertyType = propertyDescriptor.type;
  7066. var sourceProperty = entity[property];
  7067. if (sourceProperty !== undefined && sourceProperty !== null) {
  7068. switch (propertyType) {
  7069. case 0:// Value
  7070. serializationObject[targetPropertyName] = sourceProperty;
  7071. break;
  7072. case 1:// Texture
  7073. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7074. break;
  7075. case 2:// Color3
  7076. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7077. break;
  7078. case 3:// FresnelParameters
  7079. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7080. break;
  7081. case 4:// Vector2
  7082. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7083. break;
  7084. case 5:// Vector3
  7085. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7086. break;
  7087. case 6:// Mesh reference
  7088. serializationObject[targetPropertyName] = sourceProperty.id;
  7089. break;
  7090. case 7:// Color Curves
  7091. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7092. break;
  7093. case 8:// Color 4
  7094. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7095. break;
  7096. case 9:// Image Processing
  7097. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7098. break;
  7099. }
  7100. }
  7101. }
  7102. return serializationObject;
  7103. };
  7104. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7105. if (rootUrl === void 0) { rootUrl = null; }
  7106. var destination = creationFunction();
  7107. if (!rootUrl) {
  7108. rootUrl = "";
  7109. }
  7110. // Tags
  7111. if (BABYLON.Tags) {
  7112. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7113. }
  7114. var classStore = getMergedStore(destination);
  7115. // Properties
  7116. for (var property in classStore) {
  7117. var propertyDescriptor = classStore[property];
  7118. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7119. var propertyType = propertyDescriptor.type;
  7120. if (sourceProperty !== undefined && sourceProperty !== null) {
  7121. var dest = destination;
  7122. switch (propertyType) {
  7123. case 0:// Value
  7124. dest[property] = sourceProperty;
  7125. break;
  7126. case 1:// Texture
  7127. if (scene) {
  7128. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7129. }
  7130. break;
  7131. case 2:// Color3
  7132. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7133. break;
  7134. case 3:// FresnelParameters
  7135. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7136. break;
  7137. case 4:// Vector2
  7138. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7139. break;
  7140. case 5:// Vector3
  7141. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7142. break;
  7143. case 6:// Mesh reference
  7144. if (scene) {
  7145. dest[property] = scene.getLastMeshByID(sourceProperty);
  7146. }
  7147. break;
  7148. case 7:// Color Curves
  7149. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7150. break;
  7151. case 8:// Color 4
  7152. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7153. break;
  7154. case 9:// Image Processing
  7155. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. return destination;
  7161. };
  7162. SerializationHelper.Clone = function (creationFunction, source) {
  7163. return _copySource(creationFunction, source, false);
  7164. };
  7165. SerializationHelper.Instanciate = function (creationFunction, source) {
  7166. return _copySource(creationFunction, source, true);
  7167. };
  7168. return SerializationHelper;
  7169. }());
  7170. BABYLON.SerializationHelper = SerializationHelper;
  7171. })(BABYLON || (BABYLON = {}));
  7172. //# sourceMappingURL=babylon.decorators.js.map
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. /**
  7176. * Wrapper class for promise with external resolve and reject.
  7177. */
  7178. var Deferred = /** @class */ (function () {
  7179. /**
  7180. * Constructor for this deferred object.
  7181. */
  7182. function Deferred() {
  7183. var _this = this;
  7184. this.promise = new Promise(function (resolve, reject) {
  7185. _this._resolve = resolve;
  7186. _this._reject = reject;
  7187. });
  7188. }
  7189. Object.defineProperty(Deferred.prototype, "resolve", {
  7190. /**
  7191. * The resolve method of the promise associated with this deferred object.
  7192. */
  7193. get: function () {
  7194. return this._resolve;
  7195. },
  7196. enumerable: true,
  7197. configurable: true
  7198. });
  7199. Object.defineProperty(Deferred.prototype, "reject", {
  7200. /**
  7201. * The reject method of the promise associated with this deferred object.
  7202. */
  7203. get: function () {
  7204. return this._reject;
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. return Deferred;
  7210. }());
  7211. BABYLON.Deferred = Deferred;
  7212. })(BABYLON || (BABYLON = {}));
  7213. //# sourceMappingURL=babylon.deferred.js.map
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. /**
  7217. * A class serves as a medium between the observable and its observers
  7218. */
  7219. var EventState = /** @class */ (function () {
  7220. /**
  7221. * Create a new EventState
  7222. * @param mask defines the mask associated with this state
  7223. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7224. * @param target defines the original target of the state
  7225. * @param currentTarget defines the current target of the state
  7226. */
  7227. function EventState(mask, skipNextObservers, target, currentTarget) {
  7228. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7229. this.initalize(mask, skipNextObservers, target, currentTarget);
  7230. }
  7231. /**
  7232. * Initialize the current event state
  7233. * @param mask defines the mask associated with this state
  7234. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7235. * @param target defines the original target of the state
  7236. * @param currentTarget defines the current target of the state
  7237. * @returns the current event state
  7238. */
  7239. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7240. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7241. this.mask = mask;
  7242. this.skipNextObservers = skipNextObservers;
  7243. this.target = target;
  7244. this.currentTarget = currentTarget;
  7245. return this;
  7246. };
  7247. return EventState;
  7248. }());
  7249. BABYLON.EventState = EventState;
  7250. /**
  7251. * Represent an Observer registered to a given Observable object.
  7252. */
  7253. var Observer = /** @class */ (function () {
  7254. /**
  7255. * Creates a new observer
  7256. * @param callback defines the callback to call when the observer is notified
  7257. * @param mask defines the mask of the observer (used to filter notifications)
  7258. * @param scope defines the current scope used to restore the JS context
  7259. */
  7260. function Observer(
  7261. /**
  7262. * Defines the callback to call when the observer is notified
  7263. */
  7264. callback,
  7265. /**
  7266. * Defines the mask of the observer (used to filter notifications)
  7267. */
  7268. mask,
  7269. /**
  7270. * Defines the current scope used to restore the JS context
  7271. */
  7272. scope) {
  7273. if (scope === void 0) { scope = null; }
  7274. this.callback = callback;
  7275. this.mask = mask;
  7276. this.scope = scope;
  7277. /** @ignore */
  7278. this._willBeUnregistered = false;
  7279. /**
  7280. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7281. */
  7282. this.unregisterOnNextCall = false;
  7283. }
  7284. return Observer;
  7285. }());
  7286. BABYLON.Observer = Observer;
  7287. /**
  7288. * Represent a list of observers registered to multiple Observables object.
  7289. */
  7290. var MultiObserver = /** @class */ (function () {
  7291. function MultiObserver() {
  7292. }
  7293. /**
  7294. * Release associated resources
  7295. */
  7296. MultiObserver.prototype.dispose = function () {
  7297. if (this._observers && this._observables) {
  7298. for (var index = 0; index < this._observers.length; index++) {
  7299. this._observables[index].remove(this._observers[index]);
  7300. }
  7301. }
  7302. this._observers = null;
  7303. this._observables = null;
  7304. };
  7305. /**
  7306. * Raise a callback when one of the observable will notify
  7307. * @param observables defines a list of observables to watch
  7308. * @param callback defines the callback to call on notification
  7309. * @param mask defines the mask used to filter notifications
  7310. * @param scope defines the current scope used to restore the JS context
  7311. * @returns the new MultiObserver
  7312. */
  7313. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7314. if (mask === void 0) { mask = -1; }
  7315. if (scope === void 0) { scope = null; }
  7316. var result = new MultiObserver();
  7317. result._observers = new Array();
  7318. result._observables = observables;
  7319. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7320. var observable = observables_1[_i];
  7321. var observer = observable.add(callback, mask, false, scope);
  7322. if (observer) {
  7323. result._observers.push(observer);
  7324. }
  7325. }
  7326. return result;
  7327. };
  7328. return MultiObserver;
  7329. }());
  7330. BABYLON.MultiObserver = MultiObserver;
  7331. /**
  7332. * The Observable class is a simple implementation of the Observable pattern.
  7333. * 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.
  7334. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7335. * 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).
  7336. * 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.
  7337. */
  7338. var Observable = /** @class */ (function () {
  7339. /**
  7340. * Creates a new observable
  7341. * @param onObserverAdded defines a callback to call when a new observer is added
  7342. */
  7343. function Observable(onObserverAdded) {
  7344. this._observers = new Array();
  7345. this._eventState = new EventState(0);
  7346. if (onObserverAdded) {
  7347. this._onObserverAdded = onObserverAdded;
  7348. }
  7349. }
  7350. /**
  7351. * Create a new Observer with the specified callback
  7352. * @param callback the callback that will be executed for that Observer
  7353. * @param mask the mask used to filter observers
  7354. * @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.
  7355. * @param scope optional scope for the callback to be called from
  7356. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7357. * @returns the new observer created for the callback
  7358. */
  7359. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7360. if (mask === void 0) { mask = -1; }
  7361. if (insertFirst === void 0) { insertFirst = false; }
  7362. if (scope === void 0) { scope = null; }
  7363. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7364. if (!callback) {
  7365. return null;
  7366. }
  7367. var observer = new Observer(callback, mask, scope);
  7368. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7369. if (insertFirst) {
  7370. this._observers.unshift(observer);
  7371. }
  7372. else {
  7373. this._observers.push(observer);
  7374. }
  7375. if (this._onObserverAdded) {
  7376. this._onObserverAdded(observer);
  7377. }
  7378. return observer;
  7379. };
  7380. /**
  7381. * Remove an Observer from the Observable object
  7382. * @param observer the instance of the Observer to remove
  7383. * @returns false if it doesn't belong to this Observable
  7384. */
  7385. Observable.prototype.remove = function (observer) {
  7386. if (!observer) {
  7387. return false;
  7388. }
  7389. var index = this._observers.indexOf(observer);
  7390. if (index !== -1) {
  7391. this._observers.splice(index, 1);
  7392. return true;
  7393. }
  7394. return false;
  7395. };
  7396. /**
  7397. * Remove a callback from the Observable object
  7398. * @param callback the callback to remove
  7399. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7400. * @returns false if it doesn't belong to this Observable
  7401. */
  7402. Observable.prototype.removeCallback = function (callback, scope) {
  7403. for (var index = 0; index < this._observers.length; index++) {
  7404. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7405. this._observers.splice(index, 1);
  7406. return true;
  7407. }
  7408. }
  7409. return false;
  7410. };
  7411. Observable.prototype._deferUnregister = function (observer) {
  7412. var _this = this;
  7413. observer.unregisterOnNextCall = false;
  7414. observer._willBeUnregistered = true;
  7415. BABYLON.Tools.SetImmediate(function () {
  7416. _this.remove(observer);
  7417. });
  7418. };
  7419. /**
  7420. * Notify all Observers by calling their respective callback with the given data
  7421. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7422. * @param eventData defines the data to send to all observers
  7423. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7424. * @param target defines the original target of the state
  7425. * @param currentTarget defines the current target of the state
  7426. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7427. */
  7428. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7429. if (mask === void 0) { mask = -1; }
  7430. if (!this._observers.length) {
  7431. return true;
  7432. }
  7433. var state = this._eventState;
  7434. state.mask = mask;
  7435. state.target = target;
  7436. state.currentTarget = currentTarget;
  7437. state.skipNextObservers = false;
  7438. state.lastReturnValue = eventData;
  7439. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7440. var obs = _a[_i];
  7441. if (obs._willBeUnregistered) {
  7442. continue;
  7443. }
  7444. if (obs.mask & mask) {
  7445. if (obs.scope) {
  7446. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7447. }
  7448. else {
  7449. state.lastReturnValue = obs.callback(eventData, state);
  7450. }
  7451. if (obs.unregisterOnNextCall) {
  7452. this._deferUnregister(obs);
  7453. }
  7454. }
  7455. if (state.skipNextObservers) {
  7456. return false;
  7457. }
  7458. }
  7459. return true;
  7460. };
  7461. /**
  7462. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7463. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7464. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7465. * and it is crucial that all callbacks will be executed.
  7466. * The order of the callbacks is kept, callbacks are not executed parallel.
  7467. *
  7468. * @param eventData The data to be sent to each callback
  7469. * @param mask is used to filter observers defaults to -1
  7470. * @param target defines the callback target (see EventState)
  7471. * @param currentTarget defines he current object in the bubbling phase
  7472. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7473. */
  7474. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7475. var _this = this;
  7476. if (mask === void 0) { mask = -1; }
  7477. // create an empty promise
  7478. var p = Promise.resolve(eventData);
  7479. // no observers? return this promise.
  7480. if (!this._observers.length) {
  7481. return p;
  7482. }
  7483. var state = this._eventState;
  7484. state.mask = mask;
  7485. state.target = target;
  7486. state.currentTarget = currentTarget;
  7487. state.skipNextObservers = false;
  7488. // execute one callback after another (not using Promise.all, the order is important)
  7489. this._observers.forEach(function (obs) {
  7490. if (state.skipNextObservers) {
  7491. return;
  7492. }
  7493. if (obs._willBeUnregistered) {
  7494. return;
  7495. }
  7496. if (obs.mask & mask) {
  7497. if (obs.scope) {
  7498. p = p.then(function (lastReturnedValue) {
  7499. state.lastReturnValue = lastReturnedValue;
  7500. return obs.callback.apply(obs.scope, [eventData, state]);
  7501. });
  7502. }
  7503. else {
  7504. p = p.then(function (lastReturnedValue) {
  7505. state.lastReturnValue = lastReturnedValue;
  7506. return obs.callback(eventData, state);
  7507. });
  7508. }
  7509. if (obs.unregisterOnNextCall) {
  7510. _this._deferUnregister(obs);
  7511. }
  7512. }
  7513. });
  7514. // return the eventData
  7515. return p.then(function () { return eventData; });
  7516. };
  7517. /**
  7518. * Notify a specific observer
  7519. * @param observer defines the observer to notify
  7520. * @param eventData defines the data to be sent to each callback
  7521. * @param mask is used to filter observers defaults to -1
  7522. */
  7523. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7524. if (mask === void 0) { mask = -1; }
  7525. var state = this._eventState;
  7526. state.mask = mask;
  7527. state.skipNextObservers = false;
  7528. observer.callback(eventData, state);
  7529. };
  7530. /**
  7531. * Gets a boolean indicating if the observable has at least one observer
  7532. * @returns true is the Observable has at least one Observer registered
  7533. */
  7534. Observable.prototype.hasObservers = function () {
  7535. return this._observers.length > 0;
  7536. };
  7537. /**
  7538. * Clear the list of observers
  7539. */
  7540. Observable.prototype.clear = function () {
  7541. this._observers = new Array();
  7542. this._onObserverAdded = null;
  7543. };
  7544. /**
  7545. * Clone the current observable
  7546. * @returns a new observable
  7547. */
  7548. Observable.prototype.clone = function () {
  7549. var result = new Observable();
  7550. result._observers = this._observers.slice(0);
  7551. return result;
  7552. };
  7553. /**
  7554. * Does this observable handles observer registered with a given mask
  7555. * @param mask defines the mask to be tested
  7556. * @return whether or not one observer registered with the given mask is handeled
  7557. **/
  7558. Observable.prototype.hasSpecificMask = function (mask) {
  7559. if (mask === void 0) { mask = -1; }
  7560. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7561. var obs = _a[_i];
  7562. if (obs.mask & mask || obs.mask === mask) {
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. return Observable;
  7569. }());
  7570. BABYLON.Observable = Observable;
  7571. })(BABYLON || (BABYLON = {}));
  7572. //# sourceMappingURL=babylon.observable.js.map
  7573. var BABYLON;
  7574. (function (BABYLON) {
  7575. var SmartArray = /** @class */ (function () {
  7576. function SmartArray(capacity) {
  7577. this.length = 0;
  7578. this.data = new Array(capacity);
  7579. this._id = SmartArray._GlobalId++;
  7580. }
  7581. SmartArray.prototype.push = function (value) {
  7582. this.data[this.length++] = value;
  7583. if (this.length > this.data.length) {
  7584. this.data.length *= 2;
  7585. }
  7586. };
  7587. SmartArray.prototype.forEach = function (func) {
  7588. for (var index = 0; index < this.length; index++) {
  7589. func(this.data[index]);
  7590. }
  7591. };
  7592. SmartArray.prototype.sort = function (compareFn) {
  7593. this.data.sort(compareFn);
  7594. };
  7595. SmartArray.prototype.reset = function () {
  7596. this.length = 0;
  7597. };
  7598. SmartArray.prototype.dispose = function () {
  7599. this.reset();
  7600. if (this.data) {
  7601. this.data.length = 0;
  7602. this.data = [];
  7603. }
  7604. };
  7605. SmartArray.prototype.concat = function (array) {
  7606. if (array.length === 0) {
  7607. return;
  7608. }
  7609. if (this.length + array.length > this.data.length) {
  7610. this.data.length = (this.length + array.length) * 2;
  7611. }
  7612. for (var index = 0; index < array.length; index++) {
  7613. this.data[this.length++] = (array.data || array)[index];
  7614. }
  7615. };
  7616. SmartArray.prototype.indexOf = function (value) {
  7617. var position = this.data.indexOf(value);
  7618. if (position >= this.length) {
  7619. return -1;
  7620. }
  7621. return position;
  7622. };
  7623. SmartArray.prototype.contains = function (value) {
  7624. return this.data.indexOf(value) !== -1;
  7625. };
  7626. // Statics
  7627. SmartArray._GlobalId = 0;
  7628. return SmartArray;
  7629. }());
  7630. BABYLON.SmartArray = SmartArray;
  7631. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7632. __extends(SmartArrayNoDuplicate, _super);
  7633. function SmartArrayNoDuplicate() {
  7634. var _this = _super !== null && _super.apply(this, arguments) || this;
  7635. _this._duplicateId = 0;
  7636. return _this;
  7637. }
  7638. SmartArrayNoDuplicate.prototype.push = function (value) {
  7639. _super.prototype.push.call(this, value);
  7640. if (!value.__smartArrayFlags) {
  7641. value.__smartArrayFlags = {};
  7642. }
  7643. value.__smartArrayFlags[this._id] = this._duplicateId;
  7644. };
  7645. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7646. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7647. return false;
  7648. }
  7649. this.push(value);
  7650. return true;
  7651. };
  7652. SmartArrayNoDuplicate.prototype.reset = function () {
  7653. _super.prototype.reset.call(this);
  7654. this._duplicateId++;
  7655. };
  7656. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7657. if (array.length === 0) {
  7658. return;
  7659. }
  7660. if (this.length + array.length > this.data.length) {
  7661. this.data.length = (this.length + array.length) * 2;
  7662. }
  7663. for (var index = 0; index < array.length; index++) {
  7664. var item = (array.data || array)[index];
  7665. this.pushNoDuplicate(item);
  7666. }
  7667. };
  7668. return SmartArrayNoDuplicate;
  7669. }(SmartArray));
  7670. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7671. })(BABYLON || (BABYLON = {}));
  7672. //# sourceMappingURL=babylon.smartArray.js.map
  7673. var BABYLON;
  7674. (function (BABYLON) {
  7675. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7676. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7677. var LoadFileError = /** @class */ (function (_super) {
  7678. __extends(LoadFileError, _super);
  7679. function LoadFileError(message, request) {
  7680. var _this = _super.call(this, message) || this;
  7681. _this.request = request;
  7682. _this.name = "LoadFileError";
  7683. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7684. return _this;
  7685. }
  7686. // Polyfill for Object.setPrototypeOf if necessary.
  7687. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7688. return LoadFileError;
  7689. }(Error));
  7690. BABYLON.LoadFileError = LoadFileError;
  7691. var RetryStrategy = /** @class */ (function () {
  7692. function RetryStrategy() {
  7693. }
  7694. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7695. if (maxRetries === void 0) { maxRetries = 3; }
  7696. if (baseInterval === void 0) { baseInterval = 500; }
  7697. return function (url, request, retryIndex) {
  7698. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7699. return -1;
  7700. }
  7701. return Math.pow(2, retryIndex) * baseInterval;
  7702. };
  7703. };
  7704. return RetryStrategy;
  7705. }());
  7706. BABYLON.RetryStrategy = RetryStrategy;
  7707. // Screenshots
  7708. var screenshotCanvas;
  7709. var cloneValue = function (source, destinationObject) {
  7710. if (!source)
  7711. return null;
  7712. if (source instanceof BABYLON.Mesh) {
  7713. return null;
  7714. }
  7715. if (source instanceof BABYLON.SubMesh) {
  7716. return source.clone(destinationObject);
  7717. }
  7718. else if (source.clone) {
  7719. return source.clone();
  7720. }
  7721. return null;
  7722. };
  7723. var Tools = /** @class */ (function () {
  7724. function Tools() {
  7725. }
  7726. /**
  7727. * Interpolates between a and b via alpha
  7728. * @param a The lower value (returned when alpha = 0)
  7729. * @param b The upper value (returned when alpha = 1)
  7730. * @param alpha The interpolation-factor
  7731. * @return The mixed value
  7732. */
  7733. Tools.Mix = function (a, b, alpha) {
  7734. return a * (1 - alpha) + b * alpha;
  7735. };
  7736. Tools.Instantiate = function (className) {
  7737. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7738. return Tools.RegisteredExternalClasses[className];
  7739. }
  7740. var arr = className.split(".");
  7741. var fn = (window || this);
  7742. for (var i = 0, len = arr.length; i < len; i++) {
  7743. fn = fn[arr[i]];
  7744. }
  7745. if (typeof fn !== "function") {
  7746. return null;
  7747. }
  7748. return fn;
  7749. };
  7750. /**
  7751. * Provides a slice function that will work even on IE
  7752. * @param data defines the array to slice
  7753. * @returns the new sliced array
  7754. */
  7755. Tools.Slice = function (data) {
  7756. if (data.slice) {
  7757. return data.slice();
  7758. }
  7759. return Array.prototype.slice.call(data);
  7760. };
  7761. Tools.SetImmediate = function (action) {
  7762. if (window.setImmediate) {
  7763. window.setImmediate(action);
  7764. }
  7765. else {
  7766. setTimeout(action, 1);
  7767. }
  7768. };
  7769. Tools.IsExponentOfTwo = function (value) {
  7770. var count = 1;
  7771. do {
  7772. count *= 2;
  7773. } while (count < value);
  7774. return count === value;
  7775. };
  7776. /**
  7777. * Find the next highest power of two.
  7778. * @param x Number to start search from.
  7779. * @return Next highest power of two.
  7780. */
  7781. Tools.CeilingPOT = function (x) {
  7782. x--;
  7783. x |= x >> 1;
  7784. x |= x >> 2;
  7785. x |= x >> 4;
  7786. x |= x >> 8;
  7787. x |= x >> 16;
  7788. x++;
  7789. return x;
  7790. };
  7791. /**
  7792. * Find the next lowest power of two.
  7793. * @param x Number to start search from.
  7794. * @return Next lowest power of two.
  7795. */
  7796. Tools.FloorPOT = function (x) {
  7797. x = x | (x >> 1);
  7798. x = x | (x >> 2);
  7799. x = x | (x >> 4);
  7800. x = x | (x >> 8);
  7801. x = x | (x >> 16);
  7802. return x - (x >> 1);
  7803. };
  7804. /**
  7805. * Find the nearest power of two.
  7806. * @param x Number to start search from.
  7807. * @return Next nearest power of two.
  7808. */
  7809. Tools.NearestPOT = function (x) {
  7810. var c = Tools.CeilingPOT(x);
  7811. var f = Tools.FloorPOT(x);
  7812. return (c - x) > (x - f) ? f : c;
  7813. };
  7814. Tools.GetExponentOfTwo = function (value, max, mode) {
  7815. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7816. var pot;
  7817. switch (mode) {
  7818. case BABYLON.Engine.SCALEMODE_FLOOR:
  7819. pot = Tools.FloorPOT(value);
  7820. break;
  7821. case BABYLON.Engine.SCALEMODE_NEAREST:
  7822. pot = Tools.NearestPOT(value);
  7823. break;
  7824. case BABYLON.Engine.SCALEMODE_CEILING:
  7825. default:
  7826. pot = Tools.CeilingPOT(value);
  7827. break;
  7828. }
  7829. return Math.min(pot, max);
  7830. };
  7831. Tools.GetFilename = function (path) {
  7832. var index = path.lastIndexOf("/");
  7833. if (index < 0)
  7834. return path;
  7835. return path.substring(index + 1);
  7836. };
  7837. /**
  7838. * Extracts the "folder" part of a path (everything before the filename).
  7839. * @param uri The URI to extract the info from
  7840. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7841. * @returns The "folder" part of the path
  7842. */
  7843. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7844. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7845. var index = uri.lastIndexOf("/");
  7846. if (index < 0) {
  7847. if (returnUnchangedIfNoSlash) {
  7848. return uri;
  7849. }
  7850. return "";
  7851. }
  7852. return uri.substring(0, index + 1);
  7853. };
  7854. Tools.GetDOMTextContent = function (element) {
  7855. var result = "";
  7856. var child = element.firstChild;
  7857. while (child) {
  7858. if (child.nodeType === 3) {
  7859. result += child.textContent;
  7860. }
  7861. child = child.nextSibling;
  7862. }
  7863. return result;
  7864. };
  7865. Tools.ToDegrees = function (angle) {
  7866. return angle * 180 / Math.PI;
  7867. };
  7868. Tools.ToRadians = function (angle) {
  7869. return angle * Math.PI / 180;
  7870. };
  7871. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7872. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7873. var output = "";
  7874. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7875. var i = 0;
  7876. var bytes = new Uint8Array(buffer);
  7877. while (i < bytes.length) {
  7878. chr1 = bytes[i++];
  7879. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7880. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7881. enc1 = chr1 >> 2;
  7882. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7883. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7884. enc4 = chr3 & 63;
  7885. if (isNaN(chr2)) {
  7886. enc3 = enc4 = 64;
  7887. }
  7888. else if (isNaN(chr3)) {
  7889. enc4 = 64;
  7890. }
  7891. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7892. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7893. }
  7894. return "data:image/png;base64," + output;
  7895. };
  7896. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7897. if (bias === void 0) { bias = null; }
  7898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7900. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7901. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7919. if (bias === void 0) { bias = null; }
  7920. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7921. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7922. if (!stride) {
  7923. stride = 3;
  7924. }
  7925. for (var index = start; index < start + count; index++) {
  7926. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7927. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7928. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7929. }
  7930. if (bias) {
  7931. minimum.x -= minimum.x * bias.x + bias.y;
  7932. minimum.y -= minimum.y * bias.x + bias.y;
  7933. minimum.z -= minimum.z * bias.x + bias.y;
  7934. maximum.x += maximum.x * bias.x + bias.y;
  7935. maximum.y += maximum.y * bias.x + bias.y;
  7936. maximum.z += maximum.z * bias.x + bias.y;
  7937. }
  7938. return {
  7939. minimum: minimum,
  7940. maximum: maximum
  7941. };
  7942. };
  7943. Tools.Vector2ArrayFeeder = function (array) {
  7944. return function (index) {
  7945. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7946. var length = isFloatArray ? array.length / 2 : array.length;
  7947. if (index >= length) {
  7948. return null;
  7949. }
  7950. if (isFloatArray) {
  7951. var fa = array;
  7952. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7953. }
  7954. var a = array;
  7955. return a[index];
  7956. };
  7957. };
  7958. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7959. if (bias === void 0) { bias = null; }
  7960. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7961. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7962. var i = 0;
  7963. var cur = feeder(i++);
  7964. while (cur) {
  7965. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7966. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7967. cur = feeder(i++);
  7968. }
  7969. if (bias) {
  7970. minimum.x -= minimum.x * bias.x + bias.y;
  7971. minimum.y -= minimum.y * bias.x + bias.y;
  7972. maximum.x += maximum.x * bias.x + bias.y;
  7973. maximum.y += maximum.y * bias.x + bias.y;
  7974. }
  7975. return {
  7976. minimum: minimum,
  7977. maximum: maximum
  7978. };
  7979. };
  7980. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7981. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7982. return null;
  7983. return Array.isArray(obj) ? obj : [obj];
  7984. };
  7985. // Misc.
  7986. Tools.GetPointerPrefix = function () {
  7987. var eventPrefix = "pointer";
  7988. // Check if pointer events are supported
  7989. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7990. eventPrefix = "mouse";
  7991. }
  7992. return eventPrefix;
  7993. };
  7994. /**
  7995. * @param func - the function to be called
  7996. * @param requester - the object that will request the next frame. Falls back to window.
  7997. */
  7998. Tools.QueueNewFrame = function (func, requester) {
  7999. if (!Tools.IsWindowObjectExist()) {
  8000. return setTimeout(func, 16);
  8001. }
  8002. if (!requester) {
  8003. requester = window;
  8004. }
  8005. if (requester.requestAnimationFrame) {
  8006. return requester.requestAnimationFrame(func);
  8007. }
  8008. else if (requester.msRequestAnimationFrame) {
  8009. return requester.msRequestAnimationFrame(func);
  8010. }
  8011. else if (requester.webkitRequestAnimationFrame) {
  8012. return requester.webkitRequestAnimationFrame(func);
  8013. }
  8014. else if (requester.mozRequestAnimationFrame) {
  8015. return requester.mozRequestAnimationFrame(func);
  8016. }
  8017. else if (requester.oRequestAnimationFrame) {
  8018. return requester.oRequestAnimationFrame(func);
  8019. }
  8020. else {
  8021. return window.setTimeout(func, 16);
  8022. }
  8023. };
  8024. Tools.RequestFullscreen = function (element) {
  8025. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8026. if (!requestFunction)
  8027. return;
  8028. requestFunction.call(element);
  8029. };
  8030. Tools.ExitFullscreen = function () {
  8031. if (document.exitFullscreen) {
  8032. document.exitFullscreen();
  8033. }
  8034. else if (document.mozCancelFullScreen) {
  8035. document.mozCancelFullScreen();
  8036. }
  8037. else if (document.webkitCancelFullScreen) {
  8038. document.webkitCancelFullScreen();
  8039. }
  8040. else if (document.msCancelFullScreen) {
  8041. document.msCancelFullScreen();
  8042. }
  8043. };
  8044. Tools.SetCorsBehavior = function (url, element) {
  8045. if (url && url.indexOf("data:") === 0) {
  8046. return;
  8047. }
  8048. if (Tools.CorsBehavior) {
  8049. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8050. element.crossOrigin = Tools.CorsBehavior;
  8051. }
  8052. else {
  8053. var result = Tools.CorsBehavior(url);
  8054. if (result) {
  8055. element.crossOrigin = result;
  8056. }
  8057. }
  8058. }
  8059. };
  8060. // External files
  8061. Tools.CleanUrl = function (url) {
  8062. url = url.replace(/#/mg, "%23");
  8063. return url;
  8064. };
  8065. Tools.LoadImage = function (url, onLoad, onError, database) {
  8066. if (url instanceof ArrayBuffer) {
  8067. url = Tools.EncodeArrayBufferTobase64(url);
  8068. }
  8069. url = Tools.CleanUrl(url);
  8070. url = Tools.PreprocessUrl(url);
  8071. var img = new Image();
  8072. Tools.SetCorsBehavior(url, img);
  8073. var loadHandler = function () {
  8074. img.removeEventListener("load", loadHandler);
  8075. img.removeEventListener("error", errorHandler);
  8076. onLoad(img);
  8077. };
  8078. var errorHandler = function (err) {
  8079. img.removeEventListener("load", loadHandler);
  8080. img.removeEventListener("error", errorHandler);
  8081. Tools.Error("Error while trying to load image: " + url);
  8082. if (onError) {
  8083. onError("Error while trying to load image: " + url, err);
  8084. }
  8085. };
  8086. img.addEventListener("load", loadHandler);
  8087. img.addEventListener("error", errorHandler);
  8088. var noIndexedDB = function () {
  8089. img.src = url;
  8090. };
  8091. var loadFromIndexedDB = function () {
  8092. if (database) {
  8093. database.loadImageFromDB(url, img);
  8094. }
  8095. };
  8096. //ANY database to do!
  8097. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8098. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8099. }
  8100. else {
  8101. if (url.indexOf("file:") !== -1) {
  8102. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8103. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8104. try {
  8105. var blobURL;
  8106. try {
  8107. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8108. }
  8109. catch (ex) {
  8110. // Chrome doesn't support oneTimeOnly parameter
  8111. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8112. }
  8113. img.src = blobURL;
  8114. }
  8115. catch (e) {
  8116. img.src = "";
  8117. }
  8118. return img;
  8119. }
  8120. }
  8121. noIndexedDB();
  8122. }
  8123. return img;
  8124. };
  8125. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. // If file and file input are set
  8129. if (url.indexOf("file:") !== -1) {
  8130. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8131. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8132. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8133. }
  8134. }
  8135. var loadUrl = Tools.BaseUrl + url;
  8136. var aborted = false;
  8137. var fileRequest = {
  8138. onCompleteObservable: new BABYLON.Observable(),
  8139. abort: function () { return aborted = true; },
  8140. };
  8141. var requestFile = function () {
  8142. var request = new XMLHttpRequest();
  8143. var retryHandle = null;
  8144. fileRequest.abort = function () {
  8145. aborted = true;
  8146. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8147. request.abort();
  8148. }
  8149. if (retryHandle !== null) {
  8150. clearTimeout(retryHandle);
  8151. retryHandle = null;
  8152. }
  8153. };
  8154. var retryLoop = function (retryIndex) {
  8155. request.open('GET', loadUrl, true);
  8156. if (useArrayBuffer) {
  8157. request.responseType = "arraybuffer";
  8158. }
  8159. if (onProgress) {
  8160. request.addEventListener("progress", onProgress);
  8161. }
  8162. var onLoadEnd = function () {
  8163. request.removeEventListener("loadend", onLoadEnd);
  8164. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8165. fileRequest.onCompleteObservable.clear();
  8166. };
  8167. request.addEventListener("loadend", onLoadEnd);
  8168. var onReadyStateChange = function () {
  8169. if (aborted) {
  8170. return;
  8171. }
  8172. // In case of undefined state in some browsers.
  8173. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8174. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8175. request.removeEventListener("readystatechange", onReadyStateChange);
  8176. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8177. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8178. return;
  8179. }
  8180. var retryStrategy = Tools.DefaultRetryStrategy;
  8181. if (retryStrategy) {
  8182. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8183. if (waitTime !== -1) {
  8184. // Prevent the request from completing for retry.
  8185. request.removeEventListener("loadend", onLoadEnd);
  8186. request = new XMLHttpRequest();
  8187. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8188. return;
  8189. }
  8190. }
  8191. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8192. if (onError) {
  8193. onError(request, e);
  8194. }
  8195. else {
  8196. throw e;
  8197. }
  8198. }
  8199. };
  8200. request.addEventListener("readystatechange", onReadyStateChange);
  8201. request.send();
  8202. };
  8203. retryLoop(0);
  8204. };
  8205. // Caching all files
  8206. if (database && database.enableSceneOffline) {
  8207. var noIndexedDB_1 = function () {
  8208. if (!aborted) {
  8209. requestFile();
  8210. }
  8211. };
  8212. var loadFromIndexedDB = function () {
  8213. // TODO: database needs to support aborting and should return a IFileRequest
  8214. if (aborted) {
  8215. return;
  8216. }
  8217. if (database) {
  8218. database.loadFileFromDB(url, function (data) {
  8219. if (!aborted) {
  8220. onSuccess(data);
  8221. }
  8222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8223. }, onProgress ? function (event) {
  8224. if (!aborted) {
  8225. onProgress(event);
  8226. }
  8227. } : undefined, noIndexedDB_1, useArrayBuffer);
  8228. }
  8229. };
  8230. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8231. }
  8232. else {
  8233. requestFile();
  8234. }
  8235. return fileRequest;
  8236. };
  8237. /**
  8238. * Load a script (identified by an url). When the url returns, the
  8239. * content of this file is added into a new script element, attached to the DOM (body element)
  8240. */
  8241. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8242. var head = document.getElementsByTagName('head')[0];
  8243. var script = document.createElement('script');
  8244. script.type = 'text/javascript';
  8245. script.src = scriptUrl;
  8246. script.onload = function () {
  8247. if (onSuccess) {
  8248. onSuccess();
  8249. }
  8250. };
  8251. script.onerror = function (e) {
  8252. if (onError) {
  8253. onError("Unable to load script", e);
  8254. }
  8255. };
  8256. head.appendChild(script);
  8257. };
  8258. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8259. var reader = new FileReader();
  8260. var request = {
  8261. onCompleteObservable: new BABYLON.Observable(),
  8262. abort: function () { return reader.abort(); },
  8263. };
  8264. reader.onloadend = function (e) {
  8265. request.onCompleteObservable.notifyObservers(request);
  8266. };
  8267. reader.onload = function (e) {
  8268. //target doesn't have result from ts 1.3
  8269. callback(e.target['result']);
  8270. };
  8271. reader.onprogress = progressCallback;
  8272. reader.readAsDataURL(fileToLoad);
  8273. return request;
  8274. };
  8275. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8276. var reader = new FileReader();
  8277. var request = {
  8278. onCompleteObservable: new BABYLON.Observable(),
  8279. abort: function () { return reader.abort(); },
  8280. };
  8281. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8282. reader.onerror = function (e) {
  8283. Tools.Log("Error while reading file: " + fileToLoad.name);
  8284. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8285. };
  8286. reader.onload = function (e) {
  8287. //target doesn't have result from ts 1.3
  8288. callback(e.target['result']);
  8289. };
  8290. if (progressCallBack) {
  8291. reader.onprogress = progressCallBack;
  8292. }
  8293. if (!useArrayBuffer) {
  8294. // Asynchronous read
  8295. reader.readAsText(fileToLoad);
  8296. }
  8297. else {
  8298. reader.readAsArrayBuffer(fileToLoad);
  8299. }
  8300. return request;
  8301. };
  8302. //returns a downloadable url to a file content.
  8303. Tools.FileAsURL = function (content) {
  8304. var fileBlob = new Blob([content]);
  8305. var url = window.URL || window.webkitURL;
  8306. var link = url.createObjectURL(fileBlob);
  8307. return link;
  8308. };
  8309. // Misc.
  8310. Tools.Format = function (value, decimals) {
  8311. if (decimals === void 0) { decimals = 2; }
  8312. return value.toFixed(decimals);
  8313. };
  8314. Tools.CheckExtends = function (v, min, max) {
  8315. if (v.x < min.x)
  8316. min.x = v.x;
  8317. if (v.y < min.y)
  8318. min.y = v.y;
  8319. if (v.z < min.z)
  8320. min.z = v.z;
  8321. if (v.x > max.x)
  8322. max.x = v.x;
  8323. if (v.y > max.y)
  8324. max.y = v.y;
  8325. if (v.z > max.z)
  8326. max.z = v.z;
  8327. };
  8328. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8329. for (var prop in source) {
  8330. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8331. continue;
  8332. }
  8333. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8334. continue;
  8335. }
  8336. var sourceValue = source[prop];
  8337. var typeOfSourceValue = typeof sourceValue;
  8338. if (typeOfSourceValue === "function") {
  8339. continue;
  8340. }
  8341. if (typeOfSourceValue === "object") {
  8342. if (sourceValue instanceof Array) {
  8343. destination[prop] = [];
  8344. if (sourceValue.length > 0) {
  8345. if (typeof sourceValue[0] == "object") {
  8346. for (var index = 0; index < sourceValue.length; index++) {
  8347. var clonedValue = cloneValue(sourceValue[index], destination);
  8348. if (destination[prop].indexOf(clonedValue) === -1) {
  8349. destination[prop].push(clonedValue);
  8350. }
  8351. }
  8352. }
  8353. else {
  8354. destination[prop] = sourceValue.slice(0);
  8355. }
  8356. }
  8357. }
  8358. else {
  8359. destination[prop] = cloneValue(sourceValue, destination);
  8360. }
  8361. }
  8362. else {
  8363. destination[prop] = sourceValue;
  8364. }
  8365. }
  8366. };
  8367. Tools.IsEmpty = function (obj) {
  8368. for (var i in obj) {
  8369. if (obj.hasOwnProperty(i)) {
  8370. return false;
  8371. }
  8372. }
  8373. return true;
  8374. };
  8375. Tools.RegisterTopRootEvents = function (events) {
  8376. for (var index = 0; index < events.length; index++) {
  8377. var event = events[index];
  8378. window.addEventListener(event.name, event.handler, false);
  8379. try {
  8380. if (window.parent) {
  8381. window.parent.addEventListener(event.name, event.handler, false);
  8382. }
  8383. }
  8384. catch (e) {
  8385. // Silently fails...
  8386. }
  8387. }
  8388. };
  8389. Tools.UnregisterTopRootEvents = function (events) {
  8390. for (var index = 0; index < events.length; index++) {
  8391. var event = events[index];
  8392. window.removeEventListener(event.name, event.handler);
  8393. try {
  8394. if (window.parent) {
  8395. window.parent.removeEventListener(event.name, event.handler);
  8396. }
  8397. }
  8398. catch (e) {
  8399. // Silently fails...
  8400. }
  8401. }
  8402. };
  8403. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8404. if (mimeType === void 0) { mimeType = "image/png"; }
  8405. // Read the contents of the framebuffer
  8406. var numberOfChannelsByLine = width * 4;
  8407. var halfHeight = height / 2;
  8408. //Reading datas from WebGL
  8409. var data = engine.readPixels(0, 0, width, height);
  8410. //To flip image on Y axis.
  8411. for (var i = 0; i < halfHeight; i++) {
  8412. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8413. var currentCell = j + i * numberOfChannelsByLine;
  8414. var targetLine = height - i - 1;
  8415. var targetCell = j + targetLine * numberOfChannelsByLine;
  8416. var temp = data[currentCell];
  8417. data[currentCell] = data[targetCell];
  8418. data[targetCell] = temp;
  8419. }
  8420. }
  8421. // Create a 2D canvas to store the result
  8422. if (!screenshotCanvas) {
  8423. screenshotCanvas = document.createElement('canvas');
  8424. }
  8425. screenshotCanvas.width = width;
  8426. screenshotCanvas.height = height;
  8427. var context = screenshotCanvas.getContext('2d');
  8428. if (context) {
  8429. // Copy the pixels to a 2D canvas
  8430. var imageData = context.createImageData(width, height);
  8431. var castData = (imageData.data);
  8432. castData.set(data);
  8433. context.putImageData(imageData, 0, 0);
  8434. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8435. }
  8436. };
  8437. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8438. if (mimeType === void 0) { mimeType = "image/png"; }
  8439. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8440. if (successCallback) {
  8441. successCallback(base64Image);
  8442. }
  8443. else {
  8444. // We need HTMLCanvasElement.toBlob for HD screenshots
  8445. if (!screenshotCanvas.toBlob) {
  8446. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8447. screenshotCanvas.toBlob = function (callback, type, quality) {
  8448. var _this = this;
  8449. setTimeout(function () {
  8450. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8451. for (var i = 0; i < len; i++) {
  8452. arr[i] = binStr.charCodeAt(i);
  8453. }
  8454. callback(new Blob([arr], { type: type || 'image/png' }));
  8455. });
  8456. };
  8457. }
  8458. screenshotCanvas.toBlob(function (blob) {
  8459. var url = URL.createObjectURL(blob);
  8460. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8461. if (("download" in document.createElement("a"))) {
  8462. var a = window.document.createElement("a");
  8463. a.href = url;
  8464. if (fileName) {
  8465. a.setAttribute("download", fileName);
  8466. }
  8467. else {
  8468. var date = new Date();
  8469. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8470. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8471. }
  8472. window.document.body.appendChild(a);
  8473. a.addEventListener("click", function () {
  8474. if (a.parentElement) {
  8475. a.parentElement.removeChild(a);
  8476. }
  8477. });
  8478. a.click();
  8479. }
  8480. else {
  8481. var newWindow = window.open("");
  8482. if (!newWindow)
  8483. return;
  8484. var img = newWindow.document.createElement("img");
  8485. img.onload = function () {
  8486. // no longer need to read the blob so it's revoked
  8487. URL.revokeObjectURL(url);
  8488. };
  8489. img.src = url;
  8490. newWindow.document.body.appendChild(img);
  8491. }
  8492. });
  8493. }
  8494. };
  8495. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8496. if (mimeType === void 0) { mimeType = "image/png"; }
  8497. var width;
  8498. var height;
  8499. // If a precision value is specified
  8500. if (size.precision) {
  8501. width = Math.round(engine.getRenderWidth() * size.precision);
  8502. height = Math.round(width / engine.getAspectRatio(camera));
  8503. }
  8504. else if (size.width && size.height) {
  8505. width = size.width;
  8506. height = size.height;
  8507. }
  8508. else if (size.width && !size.height) {
  8509. width = size.width;
  8510. height = Math.round(width / engine.getAspectRatio(camera));
  8511. }
  8512. else if (size.height && !size.width) {
  8513. height = size.height;
  8514. width = Math.round(height * engine.getAspectRatio(camera));
  8515. }
  8516. else if (!isNaN(size)) {
  8517. height = size;
  8518. width = size;
  8519. }
  8520. else {
  8521. Tools.Error("Invalid 'size' parameter !");
  8522. return;
  8523. }
  8524. if (!screenshotCanvas) {
  8525. screenshotCanvas = document.createElement('canvas');
  8526. }
  8527. screenshotCanvas.width = width;
  8528. screenshotCanvas.height = height;
  8529. var renderContext = screenshotCanvas.getContext("2d");
  8530. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8531. var newWidth = width;
  8532. var newHeight = newWidth / ratio;
  8533. if (newHeight > height) {
  8534. newHeight = height;
  8535. newWidth = newHeight * ratio;
  8536. }
  8537. var offsetX = Math.max(0, width - newWidth) / 2;
  8538. var offsetY = Math.max(0, height - newHeight) / 2;
  8539. var renderingCanvas = engine.getRenderingCanvas();
  8540. if (renderContext && renderingCanvas) {
  8541. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8542. }
  8543. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8544. };
  8545. /**
  8546. * Generates an image screenshot from the specified camera.
  8547. *
  8548. * @param engine The engine to use for rendering
  8549. * @param camera The camera to use for rendering
  8550. * @param size This parameter can be set to a single number or to an object with the
  8551. * following (optional) properties: precision, width, height. If a single number is passed,
  8552. * it will be used for both width and height. If an object is passed, the screenshot size
  8553. * will be derived from the parameters. The precision property is a multiplier allowing
  8554. * rendering at a higher or lower resolution.
  8555. * @param successCallback The callback receives a single parameter which contains the
  8556. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8557. * src parameter of an <img> to display it.
  8558. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8559. * Check your browser for supported MIME types.
  8560. * @param samples Texture samples (default: 1)
  8561. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8562. * @param fileName A name for for the downloaded file.
  8563. * @constructor
  8564. */
  8565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8566. if (mimeType === void 0) { mimeType = "image/png"; }
  8567. if (samples === void 0) { samples = 1; }
  8568. if (antialiasing === void 0) { antialiasing = false; }
  8569. var width;
  8570. var height;
  8571. //If a precision value is specified
  8572. if (size.precision) {
  8573. width = Math.round(engine.getRenderWidth() * size.precision);
  8574. height = Math.round(width / engine.getAspectRatio(camera));
  8575. size = { width: width, height: height };
  8576. }
  8577. else if (size.width && size.height) {
  8578. width = size.width;
  8579. height = size.height;
  8580. }
  8581. else if (size.width && !size.height) {
  8582. width = size.width;
  8583. height = Math.round(width / engine.getAspectRatio(camera));
  8584. size = { width: width, height: height };
  8585. }
  8586. else if (size.height && !size.width) {
  8587. height = size.height;
  8588. width = Math.round(height * engine.getAspectRatio(camera));
  8589. size = { width: width, height: height };
  8590. }
  8591. else if (!isNaN(size)) {
  8592. height = size;
  8593. width = size;
  8594. }
  8595. else {
  8596. Tools.Error("Invalid 'size' parameter !");
  8597. return;
  8598. }
  8599. var scene = camera.getScene();
  8600. var previousCamera = null;
  8601. if (scene.activeCamera !== camera) {
  8602. previousCamera = scene.activeCamera;
  8603. scene.activeCamera = camera;
  8604. }
  8605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8607. texture.renderList = null;
  8608. texture.samples = samples;
  8609. if (antialiasing) {
  8610. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8611. }
  8612. texture.onAfterRenderObservable.add(function () {
  8613. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8614. });
  8615. scene.incrementRenderId();
  8616. scene.resetCachedMaterial();
  8617. texture.render(true);
  8618. texture.dispose();
  8619. if (previousCamera) {
  8620. scene.activeCamera = previousCamera;
  8621. }
  8622. camera.getProjectionMatrix(true); // Force cache refresh;
  8623. };
  8624. // XHR response validator for local file scenario
  8625. Tools.ValidateXHRData = function (xhr, dataType) {
  8626. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8627. if (dataType === void 0) { dataType = 7; }
  8628. try {
  8629. if (dataType & 1) {
  8630. if (xhr.responseText && xhr.responseText.length > 0) {
  8631. return true;
  8632. }
  8633. else if (dataType === 1) {
  8634. return false;
  8635. }
  8636. }
  8637. if (dataType & 2) {
  8638. // Check header width and height since there is no "TGA" magic number
  8639. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8640. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8641. return true;
  8642. }
  8643. else if (dataType === 2) {
  8644. return false;
  8645. }
  8646. }
  8647. if (dataType & 4) {
  8648. // Check for the "DDS" magic number
  8649. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8650. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8651. return true;
  8652. }
  8653. else {
  8654. return false;
  8655. }
  8656. }
  8657. }
  8658. catch (e) {
  8659. // Global protection
  8660. }
  8661. return false;
  8662. };
  8663. /**
  8664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8665. * Be aware Math.random() could cause collisions, but:
  8666. * "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"
  8667. */
  8668. Tools.RandomId = function () {
  8669. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8670. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8671. return v.toString(16);
  8672. });
  8673. };
  8674. /**
  8675. * Test if the given uri is a base64 string.
  8676. * @param uri The uri to test
  8677. * @return True if the uri is a base64 string or false otherwise.
  8678. */
  8679. Tools.IsBase64 = function (uri) {
  8680. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8681. };
  8682. /**
  8683. * Decode the given base64 uri.
  8684. * @param uri The uri to decode
  8685. * @return The decoded base64 data.
  8686. */
  8687. Tools.DecodeBase64 = function (uri) {
  8688. var decodedString = atob(uri.split(",")[1]);
  8689. var bufferLength = decodedString.length;
  8690. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8691. for (var i = 0; i < bufferLength; i++) {
  8692. bufferView[i] = decodedString.charCodeAt(i);
  8693. }
  8694. return bufferView.buffer;
  8695. };
  8696. Object.defineProperty(Tools, "NoneLogLevel", {
  8697. get: function () {
  8698. return Tools._NoneLogLevel;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(Tools, "MessageLogLevel", {
  8704. get: function () {
  8705. return Tools._MessageLogLevel;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Tools, "WarningLogLevel", {
  8711. get: function () {
  8712. return Tools._WarningLogLevel;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Object.defineProperty(Tools, "ErrorLogLevel", {
  8718. get: function () {
  8719. return Tools._ErrorLogLevel;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(Tools, "AllLogLevel", {
  8725. get: function () {
  8726. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Tools._AddLogEntry = function (entry) {
  8732. Tools._LogCache = entry + Tools._LogCache;
  8733. if (Tools.OnNewCacheEntry) {
  8734. Tools.OnNewCacheEntry(entry);
  8735. }
  8736. };
  8737. Tools._FormatMessage = function (message) {
  8738. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8739. var date = new Date();
  8740. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8741. };
  8742. Tools._LogDisabled = function (message) {
  8743. // nothing to do
  8744. };
  8745. Tools._LogEnabled = function (message) {
  8746. var formattedMessage = Tools._FormatMessage(message);
  8747. console.log("BJS - " + formattedMessage);
  8748. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8749. Tools._AddLogEntry(entry);
  8750. };
  8751. Tools._WarnDisabled = function (message) {
  8752. // nothing to do
  8753. };
  8754. Tools._WarnEnabled = function (message) {
  8755. var formattedMessage = Tools._FormatMessage(message);
  8756. console.warn("BJS - " + formattedMessage);
  8757. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8758. Tools._AddLogEntry(entry);
  8759. };
  8760. Tools._ErrorDisabled = function (message) {
  8761. // nothing to do
  8762. };
  8763. Tools._ErrorEnabled = function (message) {
  8764. Tools.errorsCount++;
  8765. var formattedMessage = Tools._FormatMessage(message);
  8766. console.error("BJS - " + formattedMessage);
  8767. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8768. Tools._AddLogEntry(entry);
  8769. };
  8770. Object.defineProperty(Tools, "LogCache", {
  8771. get: function () {
  8772. return Tools._LogCache;
  8773. },
  8774. enumerable: true,
  8775. configurable: true
  8776. });
  8777. Tools.ClearLogCache = function () {
  8778. Tools._LogCache = "";
  8779. Tools.errorsCount = 0;
  8780. };
  8781. Object.defineProperty(Tools, "LogLevels", {
  8782. set: function (level) {
  8783. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8784. Tools.Log = Tools._LogEnabled;
  8785. }
  8786. else {
  8787. Tools.Log = Tools._LogDisabled;
  8788. }
  8789. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8790. Tools.Warn = Tools._WarnEnabled;
  8791. }
  8792. else {
  8793. Tools.Warn = Tools._WarnDisabled;
  8794. }
  8795. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8796. Tools.Error = Tools._ErrorEnabled;
  8797. }
  8798. else {
  8799. Tools.Error = Tools._ErrorDisabled;
  8800. }
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Tools.IsWindowObjectExist = function () {
  8806. return (typeof window) !== "undefined";
  8807. };
  8808. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8809. get: function () {
  8810. return Tools._PerformanceNoneLogLevel;
  8811. },
  8812. enumerable: true,
  8813. configurable: true
  8814. });
  8815. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8816. get: function () {
  8817. return Tools._PerformanceUserMarkLogLevel;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8823. get: function () {
  8824. return Tools._PerformanceConsoleLogLevel;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8830. set: function (level) {
  8831. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8832. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8833. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8834. return;
  8835. }
  8836. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8837. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8838. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8839. return;
  8840. }
  8841. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8842. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8848. };
  8849. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8850. };
  8851. Tools._StartUserMark = function (counterName, condition) {
  8852. if (condition === void 0) { condition = true; }
  8853. if (!Tools._performance) {
  8854. if (!Tools.IsWindowObjectExist()) {
  8855. return;
  8856. }
  8857. Tools._performance = window.performance;
  8858. }
  8859. if (!condition || !Tools._performance.mark) {
  8860. return;
  8861. }
  8862. Tools._performance.mark(counterName + "-Begin");
  8863. };
  8864. Tools._EndUserMark = function (counterName, condition) {
  8865. if (condition === void 0) { condition = true; }
  8866. if (!condition || !Tools._performance.mark) {
  8867. return;
  8868. }
  8869. Tools._performance.mark(counterName + "-End");
  8870. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8871. };
  8872. Tools._StartPerformanceConsole = function (counterName, condition) {
  8873. if (condition === void 0) { condition = true; }
  8874. if (!condition) {
  8875. return;
  8876. }
  8877. Tools._StartUserMark(counterName, condition);
  8878. if (console.time) {
  8879. console.time(counterName);
  8880. }
  8881. };
  8882. Tools._EndPerformanceConsole = function (counterName, condition) {
  8883. if (condition === void 0) { condition = true; }
  8884. if (!condition) {
  8885. return;
  8886. }
  8887. Tools._EndUserMark(counterName, condition);
  8888. if (console.time) {
  8889. console.timeEnd(counterName);
  8890. }
  8891. };
  8892. Object.defineProperty(Tools, "Now", {
  8893. get: function () {
  8894. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8895. return window.performance.now();
  8896. }
  8897. return new Date().getTime();
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. /**
  8903. * This method will return the name of the class used to create the instance of the given object.
  8904. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8905. * @param object the object to get the class name from
  8906. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8907. */
  8908. Tools.GetClassName = function (object, isType) {
  8909. if (isType === void 0) { isType = false; }
  8910. var name = null;
  8911. if (!isType && object.getClassName) {
  8912. name = object.getClassName();
  8913. }
  8914. else {
  8915. if (object instanceof Object) {
  8916. var classObj = isType ? object : Object.getPrototypeOf(object);
  8917. name = classObj.constructor["__bjsclassName__"];
  8918. }
  8919. if (!name) {
  8920. name = typeof object;
  8921. }
  8922. }
  8923. return name;
  8924. };
  8925. Tools.First = function (array, predicate) {
  8926. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8927. var el = array_1[_i];
  8928. if (predicate(el)) {
  8929. return el;
  8930. }
  8931. }
  8932. return null;
  8933. };
  8934. /**
  8935. * This method will return the name of the full name of the class, including its owning module (if any).
  8936. * 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).
  8937. * @param object the object to get the class name from
  8938. * @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.
  8939. */
  8940. Tools.getFullClassName = function (object, isType) {
  8941. if (isType === void 0) { isType = false; }
  8942. var className = null;
  8943. var moduleName = null;
  8944. if (!isType && object.getClassName) {
  8945. className = object.getClassName();
  8946. }
  8947. else {
  8948. if (object instanceof Object) {
  8949. var classObj = isType ? object : Object.getPrototypeOf(object);
  8950. className = classObj.constructor["__bjsclassName__"];
  8951. moduleName = classObj.constructor["__bjsmoduleName__"];
  8952. }
  8953. if (!className) {
  8954. className = typeof object;
  8955. }
  8956. }
  8957. if (!className) {
  8958. return null;
  8959. }
  8960. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8961. };
  8962. /**
  8963. * 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.
  8964. * @param array
  8965. */
  8966. Tools.arrayOrStringFeeder = function (array) {
  8967. return function (index) {
  8968. if (index >= array.length) {
  8969. return null;
  8970. }
  8971. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8972. if (val && val.getHashCode) {
  8973. val = val.getHashCode();
  8974. }
  8975. if (typeof val === "string") {
  8976. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8977. }
  8978. return val;
  8979. };
  8980. };
  8981. /**
  8982. * Compute the hashCode of a stream of number
  8983. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8984. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8985. * @return the hash code computed
  8986. */
  8987. Tools.hashCodeFromStream = function (feeder) {
  8988. // Based from here: http://stackoverflow.com/a/7616484/802124
  8989. var hash = 0;
  8990. var index = 0;
  8991. var chr = feeder(index++);
  8992. while (chr != null) {
  8993. hash = ((hash << 5) - hash) + chr;
  8994. hash |= 0; // Convert to 32bit integer
  8995. chr = feeder(index++);
  8996. }
  8997. return hash;
  8998. };
  8999. /**
  9000. * Returns a promise that resolves after the given amount of time.
  9001. * @param delay Number of milliseconds to delay
  9002. * @returns Promise that resolves after the given amount of time
  9003. */
  9004. Tools.DelayAsync = function (delay) {
  9005. return new Promise(function (resolve) {
  9006. setTimeout(function () {
  9007. resolve();
  9008. }, delay);
  9009. });
  9010. };
  9011. Tools.BaseUrl = "";
  9012. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9013. /**
  9014. * Default behaviour for cors in the application.
  9015. * It can be a string if the expected behavior is identical in the entire app.
  9016. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9017. */
  9018. Tools.CorsBehavior = "anonymous";
  9019. Tools.UseFallbackTexture = true;
  9020. /**
  9021. * Use this object to register external classes like custom textures or material
  9022. * to allow the laoders to instantiate them
  9023. */
  9024. Tools.RegisteredExternalClasses = {};
  9025. // Used in case of a texture loading problem
  9026. 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";
  9027. Tools.PreprocessUrl = function (url) {
  9028. return url;
  9029. };
  9030. // Logs
  9031. Tools._NoneLogLevel = 0;
  9032. Tools._MessageLogLevel = 1;
  9033. Tools._WarningLogLevel = 2;
  9034. Tools._ErrorLogLevel = 4;
  9035. Tools._LogCache = "";
  9036. Tools.errorsCount = 0;
  9037. Tools.Log = Tools._LogEnabled;
  9038. Tools.Warn = Tools._WarnEnabled;
  9039. Tools.Error = Tools._ErrorEnabled;
  9040. // Performances
  9041. Tools._PerformanceNoneLogLevel = 0;
  9042. Tools._PerformanceUserMarkLogLevel = 1;
  9043. Tools._PerformanceConsoleLogLevel = 2;
  9044. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9045. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9046. return Tools;
  9047. }());
  9048. BABYLON.Tools = Tools;
  9049. /**
  9050. * This class is used to track a performance counter which is number based.
  9051. * The user has access to many properties which give statistics of different nature
  9052. *
  9053. * The implementer can track two kinds of Performance Counter: time and count
  9054. * 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.
  9055. * 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.
  9056. */
  9057. var PerfCounter = /** @class */ (function () {
  9058. function PerfCounter() {
  9059. this._startMonitoringTime = 0;
  9060. this._min = 0;
  9061. this._max = 0;
  9062. this._average = 0;
  9063. this._lastSecAverage = 0;
  9064. this._current = 0;
  9065. this._totalValueCount = 0;
  9066. this._totalAccumulated = 0;
  9067. this._lastSecAccumulated = 0;
  9068. this._lastSecTime = 0;
  9069. this._lastSecValueCount = 0;
  9070. }
  9071. Object.defineProperty(PerfCounter.prototype, "min", {
  9072. /**
  9073. * Returns the smallest value ever
  9074. */
  9075. get: function () {
  9076. return this._min;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(PerfCounter.prototype, "max", {
  9082. /**
  9083. * Returns the biggest value ever
  9084. */
  9085. get: function () {
  9086. return this._max;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(PerfCounter.prototype, "average", {
  9092. /**
  9093. * Returns the average value since the performance counter is running
  9094. */
  9095. get: function () {
  9096. return this._average;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9102. /**
  9103. * Returns the average value of the last second the counter was monitored
  9104. */
  9105. get: function () {
  9106. return this._lastSecAverage;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(PerfCounter.prototype, "current", {
  9112. /**
  9113. * Returns the current value
  9114. */
  9115. get: function () {
  9116. return this._current;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(PerfCounter.prototype, "total", {
  9122. get: function () {
  9123. return this._totalAccumulated;
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. Object.defineProperty(PerfCounter.prototype, "count", {
  9129. get: function () {
  9130. return this._totalValueCount;
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. /**
  9136. * Call this method to start monitoring a new frame.
  9137. * 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.
  9138. */
  9139. PerfCounter.prototype.fetchNewFrame = function () {
  9140. this._totalValueCount++;
  9141. this._current = 0;
  9142. this._lastSecValueCount++;
  9143. };
  9144. /**
  9145. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9146. * @param newCount the count value to add to the monitored count
  9147. * @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.
  9148. */
  9149. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9150. if (!PerfCounter.Enabled) {
  9151. return;
  9152. }
  9153. this._current += newCount;
  9154. if (fetchResult) {
  9155. this._fetchResult();
  9156. }
  9157. };
  9158. /**
  9159. * Start monitoring this performance counter
  9160. */
  9161. PerfCounter.prototype.beginMonitoring = function () {
  9162. if (!PerfCounter.Enabled) {
  9163. return;
  9164. }
  9165. this._startMonitoringTime = Tools.Now;
  9166. };
  9167. /**
  9168. * Compute the time lapsed since the previous beginMonitoring() call.
  9169. * @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
  9170. */
  9171. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9172. if (newFrame === void 0) { newFrame = true; }
  9173. if (!PerfCounter.Enabled) {
  9174. return;
  9175. }
  9176. if (newFrame) {
  9177. this.fetchNewFrame();
  9178. }
  9179. var currentTime = Tools.Now;
  9180. this._current = currentTime - this._startMonitoringTime;
  9181. if (newFrame) {
  9182. this._fetchResult();
  9183. }
  9184. };
  9185. PerfCounter.prototype._fetchResult = function () {
  9186. this._totalAccumulated += this._current;
  9187. this._lastSecAccumulated += this._current;
  9188. // Min/Max update
  9189. this._min = Math.min(this._min, this._current);
  9190. this._max = Math.max(this._max, this._current);
  9191. this._average = this._totalAccumulated / this._totalValueCount;
  9192. // Reset last sec?
  9193. var now = Tools.Now;
  9194. if ((now - this._lastSecTime) > 1000) {
  9195. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9196. this._lastSecTime = now;
  9197. this._lastSecAccumulated = 0;
  9198. this._lastSecValueCount = 0;
  9199. }
  9200. };
  9201. PerfCounter.Enabled = true;
  9202. return PerfCounter;
  9203. }());
  9204. BABYLON.PerfCounter = PerfCounter;
  9205. /**
  9206. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9207. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9208. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9209. * @param name The name of the class, case should be preserved
  9210. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9211. */
  9212. function className(name, module) {
  9213. return function (target) {
  9214. target["__bjsclassName__"] = name;
  9215. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9216. };
  9217. }
  9218. BABYLON.className = className;
  9219. /**
  9220. * An implementation of a loop for asynchronous functions.
  9221. */
  9222. var AsyncLoop = /** @class */ (function () {
  9223. /**
  9224. * Constroctor.
  9225. * @param iterations the number of iterations.
  9226. * @param _fn the function to run each iteration
  9227. * @param _successCallback the callback that will be called upon succesful execution
  9228. * @param offset starting offset.
  9229. */
  9230. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9231. if (offset === void 0) { offset = 0; }
  9232. this.iterations = iterations;
  9233. this._fn = _fn;
  9234. this._successCallback = _successCallback;
  9235. this.index = offset - 1;
  9236. this._done = false;
  9237. }
  9238. /**
  9239. * Execute the next iteration. Must be called after the last iteration was finished.
  9240. */
  9241. AsyncLoop.prototype.executeNext = function () {
  9242. if (!this._done) {
  9243. if (this.index + 1 < this.iterations) {
  9244. ++this.index;
  9245. this._fn(this);
  9246. }
  9247. else {
  9248. this.breakLoop();
  9249. }
  9250. }
  9251. };
  9252. /**
  9253. * Break the loop and run the success callback.
  9254. */
  9255. AsyncLoop.prototype.breakLoop = function () {
  9256. this._done = true;
  9257. this._successCallback();
  9258. };
  9259. /**
  9260. * Helper function
  9261. */
  9262. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9263. if (offset === void 0) { offset = 0; }
  9264. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9265. loop.executeNext();
  9266. return loop;
  9267. };
  9268. /**
  9269. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9270. * @param iterations total number of iterations
  9271. * @param syncedIterations number of synchronous iterations in each async iteration.
  9272. * @param fn the function to call each iteration.
  9273. * @param callback a success call back that will be called when iterating stops.
  9274. * @param breakFunction a break condition (optional)
  9275. * @param timeout timeout settings for the setTimeout function. default - 0.
  9276. * @constructor
  9277. */
  9278. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9279. if (timeout === void 0) { timeout = 0; }
  9280. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9281. if (breakFunction && breakFunction())
  9282. loop.breakLoop();
  9283. else {
  9284. setTimeout(function () {
  9285. for (var i = 0; i < syncedIterations; ++i) {
  9286. var iteration = (loop.index * syncedIterations) + i;
  9287. if (iteration >= iterations)
  9288. break;
  9289. fn(iteration);
  9290. if (breakFunction && breakFunction()) {
  9291. loop.breakLoop();
  9292. break;
  9293. }
  9294. }
  9295. loop.executeNext();
  9296. }, timeout);
  9297. }
  9298. }, callback);
  9299. };
  9300. return AsyncLoop;
  9301. }());
  9302. BABYLON.AsyncLoop = AsyncLoop;
  9303. })(BABYLON || (BABYLON = {}));
  9304. //# sourceMappingURL=babylon.tools.js.map
  9305. var BABYLON;
  9306. (function (BABYLON) {
  9307. var PromiseStates;
  9308. (function (PromiseStates) {
  9309. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9310. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9311. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9312. })(PromiseStates || (PromiseStates = {}));
  9313. var FulFillmentAgregator = /** @class */ (function () {
  9314. function FulFillmentAgregator() {
  9315. this.count = 0;
  9316. this.target = 0;
  9317. this.results = [];
  9318. }
  9319. return FulFillmentAgregator;
  9320. }());
  9321. var InternalPromise = /** @class */ (function () {
  9322. function InternalPromise(resolver) {
  9323. var _this = this;
  9324. this._state = PromiseStates.Pending;
  9325. this._children = new Array();
  9326. this._rejectWasConsumed = false;
  9327. if (!resolver) {
  9328. return;
  9329. }
  9330. try {
  9331. resolver(function (value) {
  9332. _this._resolve(value);
  9333. }, function (reason) {
  9334. _this._reject(reason);
  9335. });
  9336. }
  9337. catch (e) {
  9338. this._reject(e);
  9339. }
  9340. }
  9341. InternalPromise.prototype.catch = function (onRejected) {
  9342. return this.then(undefined, onRejected);
  9343. };
  9344. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9345. var _this = this;
  9346. var newPromise = new InternalPromise();
  9347. newPromise._onFulfilled = onFulfilled;
  9348. newPromise._onRejected = onRejected;
  9349. // Composition
  9350. this._children.push(newPromise);
  9351. if (this._state !== PromiseStates.Pending) {
  9352. BABYLON.Tools.SetImmediate(function () {
  9353. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9354. var returnedValue = newPromise._resolve(_this._result);
  9355. if (returnedValue !== undefined && returnedValue !== null) {
  9356. if (returnedValue._state !== undefined) {
  9357. var returnedPromise = returnedValue;
  9358. newPromise._children.push(returnedPromise);
  9359. newPromise = returnedPromise;
  9360. }
  9361. else {
  9362. newPromise._result = returnedValue;
  9363. }
  9364. }
  9365. }
  9366. else {
  9367. newPromise._reject(_this._reason);
  9368. }
  9369. });
  9370. }
  9371. return newPromise;
  9372. };
  9373. InternalPromise.prototype._moveChildren = function (children) {
  9374. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9375. if (this._state === PromiseStates.Fulfilled) {
  9376. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9377. var child = _b[_i];
  9378. child._resolve(this._result);
  9379. }
  9380. }
  9381. else if (this._state === PromiseStates.Rejected) {
  9382. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9383. var child = _d[_c];
  9384. child._reject(this._reason);
  9385. }
  9386. }
  9387. var _a;
  9388. };
  9389. InternalPromise.prototype._resolve = function (value) {
  9390. try {
  9391. this._state = PromiseStates.Fulfilled;
  9392. this._result = value;
  9393. var returnedValue = null;
  9394. if (this._onFulfilled) {
  9395. returnedValue = this._onFulfilled(value);
  9396. }
  9397. if (returnedValue !== undefined && returnedValue !== null) {
  9398. if (returnedValue._state !== undefined) {
  9399. // Transmit children
  9400. var returnedPromise = returnedValue;
  9401. returnedPromise._moveChildren(this._children);
  9402. }
  9403. else {
  9404. value = returnedValue;
  9405. }
  9406. }
  9407. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9408. var child = _a[_i];
  9409. child._resolve(value);
  9410. }
  9411. this._children.length = 0;
  9412. delete this._onFulfilled;
  9413. delete this._onRejected;
  9414. return returnedValue;
  9415. }
  9416. catch (e) {
  9417. this._reject(e, true);
  9418. }
  9419. return null;
  9420. };
  9421. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9422. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9423. this._state = PromiseStates.Rejected;
  9424. this._reason = reason;
  9425. if (this._onRejected && !onLocalThrow) {
  9426. try {
  9427. this._onRejected(reason);
  9428. this._rejectWasConsumed = true;
  9429. }
  9430. catch (e) {
  9431. reason = e;
  9432. }
  9433. }
  9434. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9435. var child = _a[_i];
  9436. if (this._rejectWasConsumed) {
  9437. child._resolve(null);
  9438. }
  9439. else {
  9440. child._reject(reason);
  9441. }
  9442. }
  9443. this._children.length = 0;
  9444. delete this._onFulfilled;
  9445. delete this._onRejected;
  9446. };
  9447. InternalPromise.resolve = function (value) {
  9448. var newPromise = new InternalPromise();
  9449. newPromise._resolve(value);
  9450. return newPromise;
  9451. };
  9452. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9453. promise.then(function (value) {
  9454. agregator.results[index] = value;
  9455. agregator.count++;
  9456. if (agregator.count === agregator.target) {
  9457. agregator.rootPromise._resolve(agregator.results);
  9458. }
  9459. return null;
  9460. }, function (reason) {
  9461. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9462. agregator.rootPromise._reject(reason);
  9463. }
  9464. });
  9465. };
  9466. InternalPromise.all = function (promises) {
  9467. var newPromise = new InternalPromise();
  9468. var agregator = new FulFillmentAgregator();
  9469. agregator.target = promises.length;
  9470. agregator.rootPromise = newPromise;
  9471. if (promises.length) {
  9472. for (var index = 0; index < promises.length; index++) {
  9473. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9474. }
  9475. }
  9476. else {
  9477. newPromise._resolve([]);
  9478. }
  9479. return newPromise;
  9480. };
  9481. return InternalPromise;
  9482. }());
  9483. /**
  9484. * Helper class that provides a small promise polyfill
  9485. */
  9486. var PromisePolyfill = /** @class */ (function () {
  9487. function PromisePolyfill() {
  9488. }
  9489. /**
  9490. * Static function used to check if the polyfill is required
  9491. * If this is the case then the function will inject the polyfill to window.Promise
  9492. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9493. */
  9494. PromisePolyfill.Apply = function (force) {
  9495. if (force === void 0) { force = false; }
  9496. if (force || typeof Promise === 'undefined') {
  9497. var root = window;
  9498. root.Promise = InternalPromise;
  9499. }
  9500. };
  9501. return PromisePolyfill;
  9502. }());
  9503. BABYLON.PromisePolyfill = PromisePolyfill;
  9504. })(BABYLON || (BABYLON = {}));
  9505. //# sourceMappingURL=babylon.promise.js.map
  9506. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9507. var BABYLON;
  9508. (function (BABYLON) {
  9509. /**
  9510. * Helper class to push actions to a pool of workers.
  9511. */
  9512. var WorkerPool = /** @class */ (function () {
  9513. /**
  9514. * Constructor
  9515. * @param workers Array of workers to use for actions
  9516. */
  9517. function WorkerPool(workers) {
  9518. this._pendingActions = new Array();
  9519. this._workerInfos = workers.map(function (worker) { return ({
  9520. worker: worker,
  9521. active: false
  9522. }); });
  9523. }
  9524. /**
  9525. * Terminates all workers and clears any pending actions.
  9526. */
  9527. WorkerPool.prototype.dispose = function () {
  9528. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9529. var workerInfo = _a[_i];
  9530. workerInfo.worker.terminate();
  9531. }
  9532. delete this._workerInfos;
  9533. delete this._pendingActions;
  9534. };
  9535. /**
  9536. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9537. * pended until a worker has completed its action.
  9538. * @param action The action to perform. Call onComplete when the action is complete.
  9539. */
  9540. WorkerPool.prototype.push = function (action) {
  9541. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9542. var workerInfo = _a[_i];
  9543. if (!workerInfo.active) {
  9544. this._execute(workerInfo, action);
  9545. return;
  9546. }
  9547. }
  9548. this._pendingActions.push(action);
  9549. };
  9550. WorkerPool.prototype._execute = function (workerInfo, action) {
  9551. var _this = this;
  9552. workerInfo.active = true;
  9553. action(workerInfo.worker, function () {
  9554. workerInfo.active = false;
  9555. var nextAction = _this._pendingActions.shift();
  9556. if (nextAction) {
  9557. _this._execute(workerInfo, nextAction);
  9558. }
  9559. });
  9560. };
  9561. return WorkerPool;
  9562. }());
  9563. BABYLON.WorkerPool = WorkerPool;
  9564. })(BABYLON || (BABYLON = {}));
  9565. //# sourceMappingURL=babylon.workerPool.js.map
  9566. var BABYLON;
  9567. (function (BABYLON) {
  9568. var _AlphaState = /** @class */ (function () {
  9569. /**
  9570. * Initializes the state.
  9571. */
  9572. function _AlphaState() {
  9573. this._isAlphaBlendDirty = false;
  9574. this._isBlendFunctionParametersDirty = false;
  9575. this._isBlendEquationParametersDirty = false;
  9576. this._isBlendConstantsDirty = false;
  9577. this._alphaBlend = false;
  9578. this._blendFunctionParameters = new Array(4);
  9579. this._blendEquationParameters = new Array(2);
  9580. this._blendConstants = new Array(4);
  9581. this.reset();
  9582. }
  9583. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9584. get: function () {
  9585. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9591. get: function () {
  9592. return this._alphaBlend;
  9593. },
  9594. set: function (value) {
  9595. if (this._alphaBlend === value) {
  9596. return;
  9597. }
  9598. this._alphaBlend = value;
  9599. this._isAlphaBlendDirty = true;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9605. if (this._blendConstants[0] === r &&
  9606. this._blendConstants[1] === g &&
  9607. this._blendConstants[2] === b &&
  9608. this._blendConstants[3] === a) {
  9609. return;
  9610. }
  9611. this._blendConstants[0] = r;
  9612. this._blendConstants[1] = g;
  9613. this._blendConstants[2] = b;
  9614. this._blendConstants[3] = a;
  9615. this._isBlendConstantsDirty = true;
  9616. };
  9617. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9618. if (this._blendFunctionParameters[0] === value0 &&
  9619. this._blendFunctionParameters[1] === value1 &&
  9620. this._blendFunctionParameters[2] === value2 &&
  9621. this._blendFunctionParameters[3] === value3) {
  9622. return;
  9623. }
  9624. this._blendFunctionParameters[0] = value0;
  9625. this._blendFunctionParameters[1] = value1;
  9626. this._blendFunctionParameters[2] = value2;
  9627. this._blendFunctionParameters[3] = value3;
  9628. this._isBlendFunctionParametersDirty = true;
  9629. };
  9630. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9631. if (this._blendEquationParameters[0] === rgb &&
  9632. this._blendEquationParameters[1] === alpha) {
  9633. return;
  9634. }
  9635. this._blendEquationParameters[0] = rgb;
  9636. this._blendEquationParameters[1] = alpha;
  9637. this._isBlendEquationParametersDirty = true;
  9638. };
  9639. _AlphaState.prototype.reset = function () {
  9640. this._alphaBlend = false;
  9641. this._blendFunctionParameters[0] = null;
  9642. this._blendFunctionParameters[1] = null;
  9643. this._blendFunctionParameters[2] = null;
  9644. this._blendFunctionParameters[3] = null;
  9645. this._blendEquationParameters[0] = null;
  9646. this._blendEquationParameters[1] = null;
  9647. this._blendConstants[0] = null;
  9648. this._blendConstants[1] = null;
  9649. this._blendConstants[2] = null;
  9650. this._blendConstants[3] = null;
  9651. this._isAlphaBlendDirty = true;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. };
  9656. _AlphaState.prototype.apply = function (gl) {
  9657. if (!this.isDirty) {
  9658. return;
  9659. }
  9660. // Alpha blend
  9661. if (this._isAlphaBlendDirty) {
  9662. if (this._alphaBlend) {
  9663. gl.enable(gl.BLEND);
  9664. }
  9665. else {
  9666. gl.disable(gl.BLEND);
  9667. }
  9668. this._isAlphaBlendDirty = false;
  9669. }
  9670. // Alpha function
  9671. if (this._isBlendFunctionParametersDirty) {
  9672. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9673. this._isBlendFunctionParametersDirty = false;
  9674. }
  9675. // Alpha equation
  9676. if (this._isBlendEquationParametersDirty) {
  9677. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9678. this._isBlendEquationParametersDirty = false;
  9679. }
  9680. // Constants
  9681. if (this._isBlendConstantsDirty) {
  9682. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9683. this._isBlendConstantsDirty = false;
  9684. }
  9685. };
  9686. return _AlphaState;
  9687. }());
  9688. BABYLON._AlphaState = _AlphaState;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var _DepthCullingState = /** @class */ (function () {
  9694. /**
  9695. * Initializes the state.
  9696. */
  9697. function _DepthCullingState() {
  9698. this._isDepthTestDirty = false;
  9699. this._isDepthMaskDirty = false;
  9700. this._isDepthFuncDirty = false;
  9701. this._isCullFaceDirty = false;
  9702. this._isCullDirty = false;
  9703. this._isZOffsetDirty = false;
  9704. this._isFrontFaceDirty = false;
  9705. this.reset();
  9706. }
  9707. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9708. get: function () {
  9709. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9715. get: function () {
  9716. return this._zOffset;
  9717. },
  9718. set: function (value) {
  9719. if (this._zOffset === value) {
  9720. return;
  9721. }
  9722. this._zOffset = value;
  9723. this._isZOffsetDirty = true;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9729. get: function () {
  9730. return this._cullFace;
  9731. },
  9732. set: function (value) {
  9733. if (this._cullFace === value) {
  9734. return;
  9735. }
  9736. this._cullFace = value;
  9737. this._isCullFaceDirty = true;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9743. get: function () {
  9744. return this._cull;
  9745. },
  9746. set: function (value) {
  9747. if (this._cull === value) {
  9748. return;
  9749. }
  9750. this._cull = value;
  9751. this._isCullDirty = true;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9757. get: function () {
  9758. return this._depthFunc;
  9759. },
  9760. set: function (value) {
  9761. if (this._depthFunc === value) {
  9762. return;
  9763. }
  9764. this._depthFunc = value;
  9765. this._isDepthFuncDirty = true;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9771. get: function () {
  9772. return this._depthMask;
  9773. },
  9774. set: function (value) {
  9775. if (this._depthMask === value) {
  9776. return;
  9777. }
  9778. this._depthMask = value;
  9779. this._isDepthMaskDirty = true;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9785. get: function () {
  9786. return this._depthTest;
  9787. },
  9788. set: function (value) {
  9789. if (this._depthTest === value) {
  9790. return;
  9791. }
  9792. this._depthTest = value;
  9793. this._isDepthTestDirty = true;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9799. get: function () {
  9800. return this._frontFace;
  9801. },
  9802. set: function (value) {
  9803. if (this._frontFace === value) {
  9804. return;
  9805. }
  9806. this._frontFace = value;
  9807. this._isFrontFaceDirty = true;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. _DepthCullingState.prototype.reset = function () {
  9813. this._depthMask = true;
  9814. this._depthTest = true;
  9815. this._depthFunc = null;
  9816. this._cullFace = null;
  9817. this._cull = null;
  9818. this._zOffset = 0;
  9819. this._frontFace = null;
  9820. this._isDepthTestDirty = true;
  9821. this._isDepthMaskDirty = true;
  9822. this._isDepthFuncDirty = false;
  9823. this._isCullFaceDirty = false;
  9824. this._isCullDirty = false;
  9825. this._isZOffsetDirty = false;
  9826. this._isFrontFaceDirty = false;
  9827. };
  9828. _DepthCullingState.prototype.apply = function (gl) {
  9829. if (!this.isDirty) {
  9830. return;
  9831. }
  9832. // Cull
  9833. if (this._isCullDirty) {
  9834. if (this.cull) {
  9835. gl.enable(gl.CULL_FACE);
  9836. }
  9837. else {
  9838. gl.disable(gl.CULL_FACE);
  9839. }
  9840. this._isCullDirty = false;
  9841. }
  9842. // Cull face
  9843. if (this._isCullFaceDirty) {
  9844. gl.cullFace(this.cullFace);
  9845. this._isCullFaceDirty = false;
  9846. }
  9847. // Depth mask
  9848. if (this._isDepthMaskDirty) {
  9849. gl.depthMask(this.depthMask);
  9850. this._isDepthMaskDirty = false;
  9851. }
  9852. // Depth test
  9853. if (this._isDepthTestDirty) {
  9854. if (this.depthTest) {
  9855. gl.enable(gl.DEPTH_TEST);
  9856. }
  9857. else {
  9858. gl.disable(gl.DEPTH_TEST);
  9859. }
  9860. this._isDepthTestDirty = false;
  9861. }
  9862. // Depth func
  9863. if (this._isDepthFuncDirty) {
  9864. gl.depthFunc(this.depthFunc);
  9865. this._isDepthFuncDirty = false;
  9866. }
  9867. // zOffset
  9868. if (this._isZOffsetDirty) {
  9869. if (this.zOffset) {
  9870. gl.enable(gl.POLYGON_OFFSET_FILL);
  9871. gl.polygonOffset(this.zOffset, 0);
  9872. }
  9873. else {
  9874. gl.disable(gl.POLYGON_OFFSET_FILL);
  9875. }
  9876. this._isZOffsetDirty = false;
  9877. }
  9878. // Front face
  9879. if (this._isFrontFaceDirty) {
  9880. gl.frontFace(this.frontFace);
  9881. this._isFrontFaceDirty = false;
  9882. }
  9883. };
  9884. return _DepthCullingState;
  9885. }());
  9886. BABYLON._DepthCullingState = _DepthCullingState;
  9887. })(BABYLON || (BABYLON = {}));
  9888. //# sourceMappingURL=babylon.depthCullingState.js.map
  9889. var BABYLON;
  9890. (function (BABYLON) {
  9891. var _StencilState = /** @class */ (function () {
  9892. function _StencilState() {
  9893. this._isStencilTestDirty = false;
  9894. this._isStencilMaskDirty = false;
  9895. this._isStencilFuncDirty = false;
  9896. this._isStencilOpDirty = false;
  9897. this.reset();
  9898. }
  9899. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9900. get: function () {
  9901. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9907. get: function () {
  9908. return this._stencilFunc;
  9909. },
  9910. set: function (value) {
  9911. if (this._stencilFunc === value) {
  9912. return;
  9913. }
  9914. this._stencilFunc = value;
  9915. this._isStencilFuncDirty = true;
  9916. },
  9917. enumerable: true,
  9918. configurable: true
  9919. });
  9920. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9921. get: function () {
  9922. return this._stencilFuncRef;
  9923. },
  9924. set: function (value) {
  9925. if (this._stencilFuncRef === value) {
  9926. return;
  9927. }
  9928. this._stencilFuncRef = value;
  9929. this._isStencilFuncDirty = true;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9935. get: function () {
  9936. return this._stencilFuncMask;
  9937. },
  9938. set: function (value) {
  9939. if (this._stencilFuncMask === value) {
  9940. return;
  9941. }
  9942. this._stencilFuncMask = value;
  9943. this._isStencilFuncDirty = true;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9949. get: function () {
  9950. return this._stencilOpStencilFail;
  9951. },
  9952. set: function (value) {
  9953. if (this._stencilOpStencilFail === value) {
  9954. return;
  9955. }
  9956. this._stencilOpStencilFail = value;
  9957. this._isStencilOpDirty = true;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9963. get: function () {
  9964. return this._stencilOpDepthFail;
  9965. },
  9966. set: function (value) {
  9967. if (this._stencilOpDepthFail === value) {
  9968. return;
  9969. }
  9970. this._stencilOpDepthFail = value;
  9971. this._isStencilOpDirty = true;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9977. get: function () {
  9978. return this._stencilOpStencilDepthPass;
  9979. },
  9980. set: function (value) {
  9981. if (this._stencilOpStencilDepthPass === value) {
  9982. return;
  9983. }
  9984. this._stencilOpStencilDepthPass = value;
  9985. this._isStencilOpDirty = true;
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9991. get: function () {
  9992. return this._stencilMask;
  9993. },
  9994. set: function (value) {
  9995. if (this._stencilMask === value) {
  9996. return;
  9997. }
  9998. this._stencilMask = value;
  9999. this._isStencilMaskDirty = true;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10005. get: function () {
  10006. return this._stencilTest;
  10007. },
  10008. set: function (value) {
  10009. if (this._stencilTest === value) {
  10010. return;
  10011. }
  10012. this._stencilTest = value;
  10013. this._isStencilTestDirty = true;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. _StencilState.prototype.reset = function () {
  10019. this._stencilTest = false;
  10020. this._stencilMask = 0xFF;
  10021. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10022. this._stencilFuncRef = 1;
  10023. this._stencilFuncMask = 0xFF;
  10024. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10025. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10026. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10027. this._isStencilTestDirty = true;
  10028. this._isStencilMaskDirty = true;
  10029. this._isStencilFuncDirty = true;
  10030. this._isStencilOpDirty = true;
  10031. };
  10032. _StencilState.prototype.apply = function (gl) {
  10033. if (!this.isDirty) {
  10034. return;
  10035. }
  10036. // Stencil test
  10037. if (this._isStencilTestDirty) {
  10038. if (this.stencilTest) {
  10039. gl.enable(gl.STENCIL_TEST);
  10040. }
  10041. else {
  10042. gl.disable(gl.STENCIL_TEST);
  10043. }
  10044. this._isStencilTestDirty = false;
  10045. }
  10046. // Stencil mask
  10047. if (this._isStencilMaskDirty) {
  10048. gl.stencilMask(this.stencilMask);
  10049. this._isStencilMaskDirty = false;
  10050. }
  10051. // Stencil func
  10052. if (this._isStencilFuncDirty) {
  10053. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10054. this._isStencilFuncDirty = false;
  10055. }
  10056. // Stencil op
  10057. if (this._isStencilOpDirty) {
  10058. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10059. this._isStencilOpDirty = false;
  10060. }
  10061. };
  10062. return _StencilState;
  10063. }());
  10064. BABYLON._StencilState = _StencilState;
  10065. })(BABYLON || (BABYLON = {}));
  10066. //# sourceMappingURL=babylon.stencilState.js.map
  10067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10069. s = arguments[i];
  10070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10071. t[p] = s[p];
  10072. }
  10073. return t;
  10074. };
  10075. var BABYLON;
  10076. (function (BABYLON) {
  10077. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10078. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10079. };
  10080. var compileRawShader = function (gl, source, type) {
  10081. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10082. gl.shaderSource(shader, source);
  10083. gl.compileShader(shader);
  10084. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10085. var log = gl.getShaderInfoLog(shader);
  10086. if (log) {
  10087. throw new Error(log);
  10088. }
  10089. }
  10090. if (!shader) {
  10091. throw new Error("Something went wrong while compile the shader.");
  10092. }
  10093. return shader;
  10094. };
  10095. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10096. var magFilter = gl.NEAREST;
  10097. var minFilter = gl.NEAREST;
  10098. switch (samplingMode) {
  10099. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10100. magFilter = gl.LINEAR;
  10101. if (generateMipMaps) {
  10102. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10103. }
  10104. else {
  10105. minFilter = gl.LINEAR;
  10106. }
  10107. break;
  10108. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10109. magFilter = gl.LINEAR;
  10110. if (generateMipMaps) {
  10111. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10112. }
  10113. else {
  10114. minFilter = gl.LINEAR;
  10115. }
  10116. break;
  10117. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10118. magFilter = gl.NEAREST;
  10119. if (generateMipMaps) {
  10120. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10121. }
  10122. else {
  10123. minFilter = gl.NEAREST;
  10124. }
  10125. break;
  10126. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10127. magFilter = gl.NEAREST;
  10128. if (generateMipMaps) {
  10129. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10130. }
  10131. else {
  10132. minFilter = gl.NEAREST;
  10133. }
  10134. break;
  10135. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10136. magFilter = gl.NEAREST;
  10137. if (generateMipMaps) {
  10138. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10139. }
  10140. else {
  10141. minFilter = gl.LINEAR;
  10142. }
  10143. break;
  10144. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10145. magFilter = gl.NEAREST;
  10146. if (generateMipMaps) {
  10147. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10148. }
  10149. else {
  10150. minFilter = gl.LINEAR;
  10151. }
  10152. break;
  10153. case BABYLON.Texture.NEAREST_LINEAR:
  10154. magFilter = gl.NEAREST;
  10155. minFilter = gl.LINEAR;
  10156. break;
  10157. case BABYLON.Texture.NEAREST_NEAREST:
  10158. magFilter = gl.NEAREST;
  10159. minFilter = gl.NEAREST;
  10160. break;
  10161. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10162. magFilter = gl.LINEAR;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10165. }
  10166. else {
  10167. minFilter = gl.NEAREST;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10171. magFilter = gl.LINEAR;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10174. }
  10175. else {
  10176. minFilter = gl.NEAREST;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.LINEAR_LINEAR:
  10180. magFilter = gl.LINEAR;
  10181. minFilter = gl.LINEAR;
  10182. break;
  10183. case BABYLON.Texture.LINEAR_NEAREST:
  10184. magFilter = gl.LINEAR;
  10185. minFilter = gl.NEAREST;
  10186. break;
  10187. }
  10188. return {
  10189. min: minFilter,
  10190. mag: magFilter
  10191. };
  10192. };
  10193. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10194. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10195. var img;
  10196. var onload = function () {
  10197. loadedImages[index] = img;
  10198. loadedImages._internalCount++;
  10199. if (scene) {
  10200. scene._removePendingData(img);
  10201. }
  10202. if (loadedImages._internalCount === 6) {
  10203. onfinish(loadedImages);
  10204. }
  10205. };
  10206. var onerror = function (message, exception) {
  10207. if (scene) {
  10208. scene._removePendingData(img);
  10209. }
  10210. if (onErrorCallBack) {
  10211. onErrorCallBack(message, exception);
  10212. }
  10213. };
  10214. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10215. if (scene) {
  10216. scene._addPendingData(img);
  10217. }
  10218. };
  10219. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10220. if (onError === void 0) { onError = null; }
  10221. var loadedImages = [];
  10222. loadedImages._internalCount = 0;
  10223. for (var index = 0; index < 6; index++) {
  10224. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10225. }
  10226. };
  10227. var BufferPointer = /** @class */ (function () {
  10228. function BufferPointer() {
  10229. }
  10230. return BufferPointer;
  10231. }());
  10232. var InstancingAttributeInfo = /** @class */ (function () {
  10233. function InstancingAttributeInfo() {
  10234. }
  10235. return InstancingAttributeInfo;
  10236. }());
  10237. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10238. /**
  10239. * Define options used to create a render target texture
  10240. */
  10241. var RenderTargetCreationOptions = /** @class */ (function () {
  10242. function RenderTargetCreationOptions() {
  10243. }
  10244. return RenderTargetCreationOptions;
  10245. }());
  10246. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10247. /**
  10248. * Define options used to create a depth texture
  10249. */
  10250. var DepthTextureCreationOptions = /** @class */ (function () {
  10251. function DepthTextureCreationOptions() {
  10252. }
  10253. return DepthTextureCreationOptions;
  10254. }());
  10255. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10256. /**
  10257. * Regroup several parameters relative to the browser in use
  10258. */
  10259. var EngineCapabilities = /** @class */ (function () {
  10260. function EngineCapabilities() {
  10261. }
  10262. return EngineCapabilities;
  10263. }());
  10264. BABYLON.EngineCapabilities = EngineCapabilities;
  10265. /**
  10266. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10267. */
  10268. var Engine = /** @class */ (function () {
  10269. /**
  10270. * @constructor
  10271. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10272. * @param antialias defines enable antialiasing (default: false)
  10273. * @param options defines further options to be sent to the getContext() function
  10274. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10275. */
  10276. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10277. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10278. var _this = this;
  10279. // Public members
  10280. this.forcePOTTextures = false;
  10281. this.isFullscreen = false;
  10282. this.isPointerLock = false;
  10283. this.cullBackFaces = true;
  10284. this.renderEvenInBackground = true;
  10285. this.preventCacheWipeBetweenFrames = false;
  10286. // To enable/disable IDB support and avoid XHR on .manifest
  10287. this.enableOfflineSupport = false;
  10288. this.scenes = new Array();
  10289. this.postProcesses = new Array();
  10290. // Observables
  10291. /**
  10292. * Observable event triggered each time the rendering canvas is resized
  10293. */
  10294. this.onResizeObservable = new BABYLON.Observable();
  10295. /**
  10296. * Observable event triggered each time the canvas loses focus
  10297. */
  10298. this.onCanvasBlurObservable = new BABYLON.Observable();
  10299. /**
  10300. * Observable event triggered each time the canvas gains focus
  10301. */
  10302. this.onCanvasFocusObservable = new BABYLON.Observable();
  10303. /**
  10304. * Observable event triggered each time the canvas receives pointerout event
  10305. */
  10306. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10307. /**
  10308. * Observable event triggered before each texture is initialized
  10309. */
  10310. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10311. //WebVR
  10312. this._vrDisplay = undefined;
  10313. this._vrSupported = false;
  10314. this._vrExclusivePointerMode = false;
  10315. // Uniform buffers list
  10316. this.disableUniformBuffers = false;
  10317. this._uniformBuffers = new Array();
  10318. // Observables
  10319. /**
  10320. * Observable raised when the engine begins a new frame
  10321. */
  10322. this.onBeginFrameObservable = new BABYLON.Observable();
  10323. /**
  10324. * Observable raised when the engine ends the current frame
  10325. */
  10326. this.onEndFrameObservable = new BABYLON.Observable();
  10327. /**
  10328. * Observable raised when the engine is about to compile a shader
  10329. */
  10330. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10331. /**
  10332. * Observable raised when the engine has jsut compiled a shader
  10333. */
  10334. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10335. this._windowIsBackground = false;
  10336. this._webGLVersion = 1.0;
  10337. this._badOS = false;
  10338. this._badDesktopOS = false;
  10339. /**
  10340. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10341. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10342. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10343. */
  10344. this.disableTextureBindingOptimization = false;
  10345. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10346. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10347. this.onVRRequestPresentStart = new BABYLON.Observable();
  10348. this._colorWrite = true;
  10349. this._drawCalls = new BABYLON.PerfCounter();
  10350. this._textureCollisions = new BABYLON.PerfCounter();
  10351. this._renderingQueueLaunched = false;
  10352. this._activeRenderLoops = new Array();
  10353. // Deterministic lockstepMaxSteps
  10354. this._deterministicLockstep = false;
  10355. this._lockstepMaxSteps = 4;
  10356. // Lost context
  10357. this.onContextLostObservable = new BABYLON.Observable();
  10358. this.onContextRestoredObservable = new BABYLON.Observable();
  10359. this._contextWasLost = false;
  10360. this._doNotHandleContextLost = false;
  10361. // FPS
  10362. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10363. this._fps = 60;
  10364. this._deltaTime = 0;
  10365. /**
  10366. * Turn this value on if you want to pause FPS computation when in background
  10367. */
  10368. this.disablePerformanceMonitorInBackground = false;
  10369. // States
  10370. this._depthCullingState = new BABYLON._DepthCullingState();
  10371. this._stencilState = new BABYLON._StencilState();
  10372. this._alphaState = new BABYLON._AlphaState();
  10373. this._alphaMode = Engine.ALPHA_DISABLE;
  10374. // Cache
  10375. this._internalTexturesCache = new Array();
  10376. this._activeChannel = 0;
  10377. this._currentTextureChannel = -1;
  10378. this._boundTexturesCache = {};
  10379. this._compiledEffects = {};
  10380. this._vertexAttribArraysEnabled = [];
  10381. this._uintIndicesCurrentlySet = false;
  10382. this._currentBoundBuffer = new Array();
  10383. this._currentBufferPointers = new Array();
  10384. this._currentInstanceLocations = new Array();
  10385. this._currentInstanceBuffers = new Array();
  10386. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10387. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10388. this._vaoRecordInProgress = false;
  10389. this._mustWipeVertexAttributes = false;
  10390. this._nextFreeTextureSlots = new Array();
  10391. this._maxSimultaneousTextures = 0;
  10392. this._activeRequests = new Array();
  10393. // Hardware supported Compressed Textures
  10394. this._texturesSupported = new Array();
  10395. this._onVRFullScreenTriggered = function () {
  10396. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10397. //get the old size before we change
  10398. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10399. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10400. //get the width and height, change the render size
  10401. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10402. _this.setHardwareScalingLevel(1);
  10403. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10404. }
  10405. else {
  10406. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10407. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10408. }
  10409. };
  10410. this._boundUniforms = {};
  10411. // Register promises
  10412. BABYLON.PromisePolyfill.Apply();
  10413. var canvas = null;
  10414. Engine.Instances.push(this);
  10415. if (!canvasOrContext) {
  10416. return;
  10417. }
  10418. options = options || {};
  10419. if (canvasOrContext.getContext) {
  10420. canvas = canvasOrContext;
  10421. this._renderingCanvas = canvas;
  10422. if (antialias != null) {
  10423. options.antialias = antialias;
  10424. }
  10425. if (options.deterministicLockstep === undefined) {
  10426. options.deterministicLockstep = false;
  10427. }
  10428. if (options.lockstepMaxSteps === undefined) {
  10429. options.lockstepMaxSteps = 4;
  10430. }
  10431. if (options.preserveDrawingBuffer === undefined) {
  10432. options.preserveDrawingBuffer = false;
  10433. }
  10434. if (options.audioEngine === undefined) {
  10435. options.audioEngine = true;
  10436. }
  10437. if (options.stencil === undefined) {
  10438. options.stencil = true;
  10439. }
  10440. this._deterministicLockstep = options.deterministicLockstep;
  10441. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10442. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10443. // Exceptions
  10444. if (navigator && navigator.userAgent) {
  10445. var ua = navigator.userAgent;
  10446. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10447. var exception = _a[_i];
  10448. var key = exception.key;
  10449. var targets = exception.targets;
  10450. if (ua.indexOf(key) > -1) {
  10451. if (exception.capture && exception.captureConstraint) {
  10452. var capture = exception.capture;
  10453. var constraint = exception.captureConstraint;
  10454. var regex = new RegExp(capture);
  10455. var matches = regex.exec(ua);
  10456. if (matches && matches.length > 0) {
  10457. var capturedValue = parseInt(matches[matches.length - 1]);
  10458. if (capturedValue >= constraint) {
  10459. continue;
  10460. }
  10461. }
  10462. }
  10463. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10464. var target = targets_1[_b];
  10465. switch (target) {
  10466. case "uniformBuffer":
  10467. this.disableUniformBuffers = true;
  10468. break;
  10469. case "textureBindingOptimization":
  10470. this.disableTextureBindingOptimization = true;
  10471. break;
  10472. }
  10473. }
  10474. break;
  10475. }
  10476. }
  10477. }
  10478. // GL
  10479. if (!options.disableWebGL2Support) {
  10480. try {
  10481. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10482. if (this._gl) {
  10483. this._webGLVersion = 2.0;
  10484. }
  10485. }
  10486. catch (e) {
  10487. // Do nothing
  10488. }
  10489. }
  10490. if (!this._gl) {
  10491. if (!canvas) {
  10492. throw new Error("The provided canvas is null or undefined.");
  10493. }
  10494. try {
  10495. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10496. }
  10497. catch (e) {
  10498. throw new Error("WebGL not supported");
  10499. }
  10500. }
  10501. if (!this._gl) {
  10502. throw new Error("WebGL not supported");
  10503. }
  10504. this._onCanvasFocus = function () {
  10505. _this.onCanvasFocusObservable.notifyObservers(_this);
  10506. };
  10507. this._onCanvasBlur = function () {
  10508. _this.onCanvasBlurObservable.notifyObservers(_this);
  10509. };
  10510. canvas.addEventListener("focus", this._onCanvasFocus);
  10511. canvas.addEventListener("blur", this._onCanvasBlur);
  10512. this._onBlur = function () {
  10513. if (_this.disablePerformanceMonitorInBackground) {
  10514. _this._performanceMonitor.disable();
  10515. }
  10516. _this._windowIsBackground = true;
  10517. };
  10518. this._onFocus = function () {
  10519. if (_this.disablePerformanceMonitorInBackground) {
  10520. _this._performanceMonitor.enable();
  10521. }
  10522. _this._windowIsBackground = false;
  10523. };
  10524. this._onCanvasPointerOut = function (ev) {
  10525. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10526. };
  10527. window.addEventListener("blur", this._onBlur);
  10528. window.addEventListener("focus", this._onFocus);
  10529. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10530. // Context lost
  10531. if (!this._doNotHandleContextLost) {
  10532. this._onContextLost = function (evt) {
  10533. evt.preventDefault();
  10534. _this._contextWasLost = true;
  10535. BABYLON.Tools.Warn("WebGL context lost.");
  10536. _this.onContextLostObservable.notifyObservers(_this);
  10537. };
  10538. this._onContextRestored = function (evt) {
  10539. // Adding a timeout to avoid race condition at browser level
  10540. setTimeout(function () {
  10541. // Rebuild gl context
  10542. _this._initGLContext();
  10543. // Rebuild effects
  10544. _this._rebuildEffects();
  10545. // Rebuild textures
  10546. _this._rebuildInternalTextures();
  10547. // Rebuild buffers
  10548. _this._rebuildBuffers();
  10549. // Cache
  10550. _this.wipeCaches(true);
  10551. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10552. _this.onContextRestoredObservable.notifyObservers(_this);
  10553. _this._contextWasLost = false;
  10554. }, 0);
  10555. };
  10556. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10557. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10558. }
  10559. }
  10560. else {
  10561. this._gl = canvasOrContext;
  10562. this._renderingCanvas = this._gl.canvas;
  10563. if (this._gl.renderbufferStorageMultisample) {
  10564. this._webGLVersion = 2.0;
  10565. }
  10566. options.stencil = this._gl.getContextAttributes().stencil;
  10567. }
  10568. // Viewport
  10569. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10570. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10571. this.resize();
  10572. this._isStencilEnable = options.stencil ? true : false;
  10573. this._initGLContext();
  10574. if (canvas) {
  10575. // Fullscreen
  10576. this._onFullscreenChange = function () {
  10577. if (document.fullscreen !== undefined) {
  10578. _this.isFullscreen = document.fullscreen;
  10579. }
  10580. else if (document.mozFullScreen !== undefined) {
  10581. _this.isFullscreen = document.mozFullScreen;
  10582. }
  10583. else if (document.webkitIsFullScreen !== undefined) {
  10584. _this.isFullscreen = document.webkitIsFullScreen;
  10585. }
  10586. else if (document.msIsFullScreen !== undefined) {
  10587. _this.isFullscreen = document.msIsFullScreen;
  10588. }
  10589. // Pointer lock
  10590. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10591. canvas.requestPointerLock = canvas.requestPointerLock ||
  10592. canvas.msRequestPointerLock ||
  10593. canvas.mozRequestPointerLock ||
  10594. canvas.webkitRequestPointerLock;
  10595. if (canvas.requestPointerLock) {
  10596. canvas.requestPointerLock();
  10597. }
  10598. }
  10599. };
  10600. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10601. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10602. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10603. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10604. // Pointer lock
  10605. this._onPointerLockChange = function () {
  10606. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10607. document.webkitPointerLockElement === canvas ||
  10608. document.msPointerLockElement === canvas ||
  10609. document.pointerLockElement === canvas);
  10610. };
  10611. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10612. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10613. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10614. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10615. this._onVRDisplayPointerRestricted = function () {
  10616. if (canvas) {
  10617. canvas.requestPointerLock();
  10618. }
  10619. };
  10620. this._onVRDisplayPointerUnrestricted = function () {
  10621. document.exitPointerLock();
  10622. };
  10623. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10624. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10625. }
  10626. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10627. Engine.audioEngine = new BABYLON.AudioEngine();
  10628. }
  10629. // Prepare buffer pointers
  10630. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10631. this._currentBufferPointers[i] = new BufferPointer();
  10632. }
  10633. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10634. // Load WebVR Devices
  10635. if (options.autoEnableWebVR) {
  10636. this.initWebVR();
  10637. }
  10638. // Detect if we are running on a faulty buggy OS.
  10639. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10640. // Detect if we are running on a faulty buggy desktop OS.
  10641. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10642. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10643. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10644. }
  10645. Object.defineProperty(Engine, "LastCreatedEngine", {
  10646. get: function () {
  10647. if (Engine.Instances.length === 0) {
  10648. return null;
  10649. }
  10650. return Engine.Instances[Engine.Instances.length - 1];
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "LastCreatedScene", {
  10656. get: function () {
  10657. var lastCreatedEngine = Engine.LastCreatedEngine;
  10658. if (!lastCreatedEngine) {
  10659. return null;
  10660. }
  10661. if (lastCreatedEngine.scenes.length === 0) {
  10662. return null;
  10663. }
  10664. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. /**
  10670. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10671. */
  10672. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10673. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10674. var engine = Engine.Instances[engineIndex];
  10675. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10676. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10677. }
  10678. }
  10679. };
  10680. Object.defineProperty(Engine, "NEVER", {
  10681. get: function () {
  10682. return Engine._NEVER;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(Engine, "ALWAYS", {
  10688. get: function () {
  10689. return Engine._ALWAYS;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(Engine, "LESS", {
  10695. get: function () {
  10696. return Engine._LESS;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(Engine, "EQUAL", {
  10702. get: function () {
  10703. return Engine._EQUAL;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(Engine, "LEQUAL", {
  10709. get: function () {
  10710. return Engine._LEQUAL;
  10711. },
  10712. enumerable: true,
  10713. configurable: true
  10714. });
  10715. Object.defineProperty(Engine, "GREATER", {
  10716. get: function () {
  10717. return Engine._GREATER;
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(Engine, "GEQUAL", {
  10723. get: function () {
  10724. return Engine._GEQUAL;
  10725. },
  10726. enumerable: true,
  10727. configurable: true
  10728. });
  10729. Object.defineProperty(Engine, "NOTEQUAL", {
  10730. get: function () {
  10731. return Engine._NOTEQUAL;
  10732. },
  10733. enumerable: true,
  10734. configurable: true
  10735. });
  10736. Object.defineProperty(Engine, "KEEP", {
  10737. get: function () {
  10738. return Engine._KEEP;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Engine, "REPLACE", {
  10744. get: function () {
  10745. return Engine._REPLACE;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Engine, "INCR", {
  10751. get: function () {
  10752. return Engine._INCR;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Engine, "DECR", {
  10758. get: function () {
  10759. return Engine._DECR;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "INVERT", {
  10765. get: function () {
  10766. return Engine._INVERT;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "INCR_WRAP", {
  10772. get: function () {
  10773. return Engine._INCR_WRAP;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "DECR_WRAP", {
  10779. get: function () {
  10780. return Engine._DECR_WRAP;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10786. get: function () {
  10787. return Engine._ALPHA_DISABLE;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10793. get: function () {
  10794. return Engine._ALPHA_ONEONE;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "ALPHA_ADD", {
  10800. get: function () {
  10801. return Engine._ALPHA_ADD;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10807. get: function () {
  10808. return Engine._ALPHA_COMBINE;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10814. get: function () {
  10815. return Engine._ALPHA_SUBTRACT;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10821. get: function () {
  10822. return Engine._ALPHA_MULTIPLY;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10828. get: function () {
  10829. return Engine._ALPHA_MAXIMIZED;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10835. get: function () {
  10836. return Engine._ALPHA_PREMULTIPLIED;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10842. get: function () {
  10843. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10849. get: function () {
  10850. return Engine._ALPHA_INTERPOLATE;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10856. get: function () {
  10857. return Engine._ALPHA_SCREENMODE;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10863. get: function () {
  10864. return Engine._DELAYLOADSTATE_NONE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10870. get: function () {
  10871. return Engine._DELAYLOADSTATE_LOADED;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10877. get: function () {
  10878. return Engine._DELAYLOADSTATE_LOADING;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10884. get: function () {
  10885. return Engine._DELAYLOADSTATE_NOTLOADED;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10891. get: function () {
  10892. return Engine._TEXTUREFORMAT_ALPHA;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10898. get: function () {
  10899. return Engine._TEXTUREFORMAT_LUMINANCE;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10905. /**
  10906. * R32F
  10907. */
  10908. get: function () {
  10909. return Engine._TEXTUREFORMAT_R32F;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10915. /**
  10916. * RG32F
  10917. */
  10918. get: function () {
  10919. return Engine._TEXTUREFORMAT_RG32F;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10925. /**
  10926. * RGB32F
  10927. */
  10928. get: function () {
  10929. return Engine._TEXTUREFORMAT_RGB32F;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10935. /**
  10936. * RGBA32F
  10937. */
  10938. get: function () {
  10939. return Engine._TEXTUREFORMAT_RGBA32F;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10945. get: function () {
  10946. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10952. get: function () {
  10953. return Engine._TEXTUREFORMAT_RGB;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10959. get: function () {
  10960. return Engine._TEXTUREFORMAT_RGBA;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10966. get: function () {
  10967. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10973. get: function () {
  10974. return Engine._TEXTURETYPE_FLOAT;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10980. get: function () {
  10981. return Engine._TEXTURETYPE_HALF_FLOAT;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10987. get: function () {
  10988. return Engine._SCALEMODE_FLOOR;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10994. get: function () {
  10995. return Engine._SCALEMODE_NEAREST;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11001. get: function () {
  11002. return Engine._SCALEMODE_CEILING;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "Version", {
  11008. get: function () {
  11009. return "3.2.0-alphaA";
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11015. get: function () {
  11016. return this._vrExclusivePointerMode;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11022. get: function () {
  11023. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11029. get: function () {
  11030. return this._webGLVersion < 2 || this.forcePOTTextures;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine.prototype, "badOS", {
  11036. get: function () {
  11037. return this._badOS;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11043. get: function () {
  11044. return this._badDesktopOS;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11050. get: function () {
  11051. return this._performanceMonitor;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11057. get: function () {
  11058. return this._texturesSupported;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11064. get: function () {
  11065. return this._textureFormatInUse;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine.prototype, "currentViewport", {
  11071. get: function () {
  11072. return this._cachedViewport;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11078. // Empty texture
  11079. get: function () {
  11080. if (!this._emptyTexture) {
  11081. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11082. }
  11083. return this._emptyTexture;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11089. get: function () {
  11090. if (!this._emptyTexture3D) {
  11091. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11092. }
  11093. return this._emptyTexture3D;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11099. get: function () {
  11100. if (!this._emptyCubeTexture) {
  11101. var faceData = new Uint8Array(4);
  11102. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11103. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11104. }
  11105. return this._emptyCubeTexture;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Engine.prototype._rebuildInternalTextures = function () {
  11111. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11112. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11113. var internalTexture = currentState_1[_i];
  11114. internalTexture._rebuild();
  11115. }
  11116. };
  11117. Engine.prototype._rebuildEffects = function () {
  11118. for (var key in this._compiledEffects) {
  11119. var effect = this._compiledEffects[key];
  11120. effect._prepareEffect();
  11121. }
  11122. BABYLON.Effect.ResetCache();
  11123. };
  11124. Engine.prototype._rebuildBuffers = function () {
  11125. // Index / Vertex
  11126. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11127. var scene = _a[_i];
  11128. scene.resetCachedMaterial();
  11129. scene._rebuildGeometries();
  11130. scene._rebuildTextures();
  11131. }
  11132. // Uniforms
  11133. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11134. var uniformBuffer = _c[_b];
  11135. uniformBuffer._rebuild();
  11136. }
  11137. };
  11138. Engine.prototype._initGLContext = function () {
  11139. // Caps
  11140. this._caps = new EngineCapabilities();
  11141. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11142. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11143. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11144. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11145. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11146. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11147. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11148. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11149. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11150. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11151. // Infos
  11152. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11153. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11154. if (rendererInfo != null) {
  11155. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11156. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11157. }
  11158. if (!this._glVendor) {
  11159. this._glVendor = "Unknown vendor";
  11160. }
  11161. if (!this._glRenderer) {
  11162. this._glRenderer = "Unknown renderer";
  11163. }
  11164. // Constants
  11165. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11166. if (this._gl.RGBA16F !== 0x881A) {
  11167. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11168. }
  11169. if (this._gl.RGBA32F !== 0x8814) {
  11170. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11171. }
  11172. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11173. this._gl.DEPTH24_STENCIL8 = 35056;
  11174. }
  11175. // Extensions
  11176. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11177. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11178. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11179. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11180. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11181. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11182. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11183. 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');
  11184. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11185. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11186. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11187. this._caps.highPrecisionShaderSupported = true;
  11188. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11189. if (this._caps.timerQuery) {
  11190. if (this._webGLVersion === 1) {
  11191. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11192. }
  11193. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11194. }
  11195. // Checks if some of the format renders first to allow the use of webgl inspector.
  11196. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11197. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11198. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11199. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11200. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11201. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11202. if (this._webGLVersion > 1) {
  11203. this._gl.HALF_FLOAT_OES = 0x140B;
  11204. }
  11205. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11206. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11207. // Draw buffers
  11208. if (this._webGLVersion > 1) {
  11209. this._caps.drawBuffersExtension = true;
  11210. }
  11211. else {
  11212. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11213. if (drawBuffersExtension !== null) {
  11214. this._caps.drawBuffersExtension = true;
  11215. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11216. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11217. for (var i = 0; i < 16; i++) {
  11218. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11219. }
  11220. }
  11221. else {
  11222. this._caps.drawBuffersExtension = false;
  11223. }
  11224. }
  11225. // Depth Texture
  11226. if (this._webGLVersion > 1) {
  11227. this._caps.depthTextureExtension = true;
  11228. }
  11229. else {
  11230. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11231. if (depthTextureExtension != null) {
  11232. this._caps.depthTextureExtension = true;
  11233. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11234. }
  11235. }
  11236. // Vertex array object
  11237. if (this._webGLVersion > 1) {
  11238. this._caps.vertexArrayObject = true;
  11239. }
  11240. else {
  11241. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11242. if (vertexArrayObjectExtension != null) {
  11243. this._caps.vertexArrayObject = true;
  11244. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11245. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11246. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11247. }
  11248. else {
  11249. this._caps.vertexArrayObject = false;
  11250. }
  11251. }
  11252. // Instances count
  11253. if (this._webGLVersion > 1) {
  11254. this._caps.instancedArrays = true;
  11255. }
  11256. else {
  11257. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11258. if (instanceExtension != null) {
  11259. this._caps.instancedArrays = true;
  11260. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11261. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11262. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11263. }
  11264. else {
  11265. this._caps.instancedArrays = false;
  11266. }
  11267. }
  11268. // Intelligently add supported compressed formats in order to check for.
  11269. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11270. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11271. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11272. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11273. if (this._caps.astc)
  11274. this.texturesSupported.push('-astc.ktx');
  11275. if (this._caps.s3tc)
  11276. this.texturesSupported.push('-dxt.ktx');
  11277. if (this._caps.pvrtc)
  11278. this.texturesSupported.push('-pvrtc.ktx');
  11279. if (this._caps.etc2)
  11280. this.texturesSupported.push('-etc2.ktx');
  11281. if (this._caps.etc1)
  11282. this.texturesSupported.push('-etc1.ktx');
  11283. if (this._gl.getShaderPrecisionFormat) {
  11284. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11285. if (highp) {
  11286. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11287. }
  11288. }
  11289. // Depth buffer
  11290. this.setDepthBuffer(true);
  11291. this.setDepthFunctionToLessOrEqual();
  11292. this.setDepthWrite(true);
  11293. // Texture maps
  11294. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11295. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11296. this._nextFreeTextureSlots.push(slot);
  11297. }
  11298. };
  11299. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11300. get: function () {
  11301. return this._webGLVersion;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11307. /**
  11308. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11309. */
  11310. get: function () {
  11311. return this._isStencilEnable;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Engine.prototype._prepareWorkingCanvas = function () {
  11317. if (this._workingCanvas) {
  11318. return;
  11319. }
  11320. this._workingCanvas = document.createElement("canvas");
  11321. var context = this._workingCanvas.getContext("2d");
  11322. if (context) {
  11323. this._workingContext = context;
  11324. }
  11325. };
  11326. Engine.prototype.resetTextureCache = function () {
  11327. for (var key in this._boundTexturesCache) {
  11328. var boundTexture = this._boundTexturesCache[key];
  11329. if (boundTexture) {
  11330. this._removeDesignatedSlot(boundTexture);
  11331. }
  11332. this._boundTexturesCache[key] = null;
  11333. }
  11334. if (!this.disableTextureBindingOptimization) {
  11335. this._nextFreeTextureSlots = [];
  11336. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11337. this._nextFreeTextureSlots.push(slot);
  11338. }
  11339. }
  11340. this._currentTextureChannel = -1;
  11341. };
  11342. Engine.prototype.isDeterministicLockStep = function () {
  11343. return this._deterministicLockstep;
  11344. };
  11345. Engine.prototype.getLockstepMaxSteps = function () {
  11346. return this._lockstepMaxSteps;
  11347. };
  11348. Engine.prototype.getGlInfo = function () {
  11349. return {
  11350. vendor: this._glVendor,
  11351. renderer: this._glRenderer,
  11352. version: this._glVersion
  11353. };
  11354. };
  11355. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11356. if (useScreen === void 0) { useScreen = false; }
  11357. var viewport = camera.viewport;
  11358. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11359. };
  11360. Engine.prototype.getRenderWidth = function (useScreen) {
  11361. if (useScreen === void 0) { useScreen = false; }
  11362. if (!useScreen && this._currentRenderTarget) {
  11363. return this._currentRenderTarget.width;
  11364. }
  11365. return this._gl.drawingBufferWidth;
  11366. };
  11367. Engine.prototype.getRenderHeight = function (useScreen) {
  11368. if (useScreen === void 0) { useScreen = false; }
  11369. if (!useScreen && this._currentRenderTarget) {
  11370. return this._currentRenderTarget.height;
  11371. }
  11372. return this._gl.drawingBufferHeight;
  11373. };
  11374. Engine.prototype.getRenderingCanvas = function () {
  11375. return this._renderingCanvas;
  11376. };
  11377. Engine.prototype.getRenderingCanvasClientRect = function () {
  11378. if (!this._renderingCanvas) {
  11379. return null;
  11380. }
  11381. return this._renderingCanvas.getBoundingClientRect();
  11382. };
  11383. Engine.prototype.setHardwareScalingLevel = function (level) {
  11384. this._hardwareScalingLevel = level;
  11385. this.resize();
  11386. };
  11387. Engine.prototype.getHardwareScalingLevel = function () {
  11388. return this._hardwareScalingLevel;
  11389. };
  11390. Engine.prototype.getLoadedTexturesCache = function () {
  11391. return this._internalTexturesCache;
  11392. };
  11393. Engine.prototype.getCaps = function () {
  11394. return this._caps;
  11395. };
  11396. Object.defineProperty(Engine.prototype, "drawCalls", {
  11397. /** The number of draw calls submitted last frame */
  11398. get: function () {
  11399. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11400. return 0;
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11406. get: function () {
  11407. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11408. return null;
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Engine.prototype.getDepthFunction = function () {
  11414. return this._depthCullingState.depthFunc;
  11415. };
  11416. Engine.prototype.setDepthFunction = function (depthFunc) {
  11417. this._depthCullingState.depthFunc = depthFunc;
  11418. };
  11419. Engine.prototype.setDepthFunctionToGreater = function () {
  11420. this._depthCullingState.depthFunc = this._gl.GREATER;
  11421. };
  11422. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11423. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11424. };
  11425. Engine.prototype.setDepthFunctionToLess = function () {
  11426. this._depthCullingState.depthFunc = this._gl.LESS;
  11427. };
  11428. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11429. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11430. };
  11431. Engine.prototype.getStencilBuffer = function () {
  11432. return this._stencilState.stencilTest;
  11433. };
  11434. Engine.prototype.setStencilBuffer = function (enable) {
  11435. this._stencilState.stencilTest = enable;
  11436. };
  11437. Engine.prototype.getStencilMask = function () {
  11438. return this._stencilState.stencilMask;
  11439. };
  11440. Engine.prototype.setStencilMask = function (mask) {
  11441. this._stencilState.stencilMask = mask;
  11442. };
  11443. Engine.prototype.getStencilFunction = function () {
  11444. return this._stencilState.stencilFunc;
  11445. };
  11446. Engine.prototype.getStencilFunctionReference = function () {
  11447. return this._stencilState.stencilFuncRef;
  11448. };
  11449. Engine.prototype.getStencilFunctionMask = function () {
  11450. return this._stencilState.stencilFuncMask;
  11451. };
  11452. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11453. this._stencilState.stencilFunc = stencilFunc;
  11454. };
  11455. Engine.prototype.setStencilFunctionReference = function (reference) {
  11456. this._stencilState.stencilFuncRef = reference;
  11457. };
  11458. Engine.prototype.setStencilFunctionMask = function (mask) {
  11459. this._stencilState.stencilFuncMask = mask;
  11460. };
  11461. Engine.prototype.getStencilOperationFail = function () {
  11462. return this._stencilState.stencilOpStencilFail;
  11463. };
  11464. Engine.prototype.getStencilOperationDepthFail = function () {
  11465. return this._stencilState.stencilOpDepthFail;
  11466. };
  11467. Engine.prototype.getStencilOperationPass = function () {
  11468. return this._stencilState.stencilOpStencilDepthPass;
  11469. };
  11470. Engine.prototype.setStencilOperationFail = function (operation) {
  11471. this._stencilState.stencilOpStencilFail = operation;
  11472. };
  11473. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11474. this._stencilState.stencilOpDepthFail = operation;
  11475. };
  11476. Engine.prototype.setStencilOperationPass = function (operation) {
  11477. this._stencilState.stencilOpStencilDepthPass = operation;
  11478. };
  11479. Engine.prototype.setDitheringState = function (value) {
  11480. if (value) {
  11481. this._gl.enable(this._gl.DITHER);
  11482. }
  11483. else {
  11484. this._gl.disable(this._gl.DITHER);
  11485. }
  11486. };
  11487. Engine.prototype.setRasterizerState = function (value) {
  11488. if (value) {
  11489. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11490. }
  11491. else {
  11492. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11493. }
  11494. };
  11495. /**
  11496. * stop executing a render loop function and remove it from the execution array
  11497. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11498. */
  11499. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11500. if (!renderFunction) {
  11501. this._activeRenderLoops = [];
  11502. return;
  11503. }
  11504. var index = this._activeRenderLoops.indexOf(renderFunction);
  11505. if (index >= 0) {
  11506. this._activeRenderLoops.splice(index, 1);
  11507. }
  11508. };
  11509. Engine.prototype._renderLoop = function () {
  11510. if (!this._contextWasLost) {
  11511. var shouldRender = true;
  11512. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11513. shouldRender = false;
  11514. }
  11515. if (shouldRender) {
  11516. // Start new frame
  11517. this.beginFrame();
  11518. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11519. var renderFunction = this._activeRenderLoops[index];
  11520. renderFunction();
  11521. }
  11522. // Present
  11523. this.endFrame();
  11524. }
  11525. }
  11526. if (this._activeRenderLoops.length > 0) {
  11527. // Register new frame
  11528. var requester = null;
  11529. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11530. requester = this._vrDisplay;
  11531. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11532. }
  11533. else {
  11534. this._renderingQueueLaunched = false;
  11535. }
  11536. };
  11537. /**
  11538. * Register and execute a render loop. The engine can have more than one render function.
  11539. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11540. * @example
  11541. * engine.runRenderLoop(function () {
  11542. * scene.render()
  11543. * })
  11544. */
  11545. Engine.prototype.runRenderLoop = function (renderFunction) {
  11546. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11547. return;
  11548. }
  11549. this._activeRenderLoops.push(renderFunction);
  11550. if (!this._renderingQueueLaunched) {
  11551. this._renderingQueueLaunched = true;
  11552. this._bindedRenderFunction = this._renderLoop.bind(this);
  11553. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11554. }
  11555. };
  11556. /**
  11557. * Toggle full screen mode.
  11558. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11559. * @param {any} options - an options object to be sent to the requestFullscreen function
  11560. */
  11561. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11562. if (this.isFullscreen) {
  11563. BABYLON.Tools.ExitFullscreen();
  11564. }
  11565. else {
  11566. this._pointerLockRequested = requestPointerLock;
  11567. if (this._renderingCanvas) {
  11568. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11569. }
  11570. }
  11571. };
  11572. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11573. if (stencil === void 0) { stencil = false; }
  11574. this.applyStates();
  11575. var mode = 0;
  11576. if (backBuffer && color) {
  11577. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11578. mode |= this._gl.COLOR_BUFFER_BIT;
  11579. }
  11580. if (depth) {
  11581. this._gl.clearDepth(1.0);
  11582. mode |= this._gl.DEPTH_BUFFER_BIT;
  11583. }
  11584. if (stencil) {
  11585. this._gl.clearStencil(0);
  11586. mode |= this._gl.STENCIL_BUFFER_BIT;
  11587. }
  11588. this._gl.clear(mode);
  11589. };
  11590. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11591. var gl = this._gl;
  11592. // Save state
  11593. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11594. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11595. // Change state
  11596. gl.enable(gl.SCISSOR_TEST);
  11597. gl.scissor(x, y, width, height);
  11598. // Clear
  11599. this.clear(clearColor, true, true, true);
  11600. // Restore state
  11601. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11602. if (curScissor === true) {
  11603. gl.enable(gl.SCISSOR_TEST);
  11604. }
  11605. else {
  11606. gl.disable(gl.SCISSOR_TEST);
  11607. }
  11608. };
  11609. /**
  11610. * Set the WebGL's viewport
  11611. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11612. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11613. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11614. */
  11615. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11616. var width = requiredWidth || this.getRenderWidth();
  11617. var height = requiredHeight || this.getRenderHeight();
  11618. var x = viewport.x || 0;
  11619. var y = viewport.y || 0;
  11620. this._cachedViewport = viewport;
  11621. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11622. };
  11623. /**
  11624. * Directly set the WebGL Viewport
  11625. * The x, y, width & height are directly passed to the WebGL call
  11626. * @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.
  11627. */
  11628. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11629. var currentViewport = this._cachedViewport;
  11630. this._cachedViewport = null;
  11631. this._gl.viewport(x, y, width, height);
  11632. return currentViewport;
  11633. };
  11634. Engine.prototype.beginFrame = function () {
  11635. this.onBeginFrameObservable.notifyObservers(this);
  11636. this._measureFps();
  11637. };
  11638. Engine.prototype.endFrame = function () {
  11639. //force a flush in case we are using a bad OS.
  11640. if (this._badOS) {
  11641. this.flushFramebuffer();
  11642. }
  11643. //submit frame to the vr device, if enabled
  11644. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11645. // TODO: We should only submit the frame if we read frameData successfully.
  11646. this._vrDisplay.submitFrame();
  11647. }
  11648. this.onEndFrameObservable.notifyObservers(this);
  11649. };
  11650. /**
  11651. * resize the view according to the canvas' size.
  11652. * @example
  11653. * window.addEventListener("resize", function () {
  11654. * engine.resize();
  11655. * });
  11656. */
  11657. Engine.prototype.resize = function () {
  11658. // We're not resizing the size of the canvas while in VR mode & presenting
  11659. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11660. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11661. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11662. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11663. }
  11664. };
  11665. /**
  11666. * force a specific size of the canvas
  11667. * @param {number} width - the new canvas' width
  11668. * @param {number} height - the new canvas' height
  11669. */
  11670. Engine.prototype.setSize = function (width, height) {
  11671. if (!this._renderingCanvas) {
  11672. return;
  11673. }
  11674. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11675. return;
  11676. }
  11677. this._renderingCanvas.width = width;
  11678. this._renderingCanvas.height = height;
  11679. for (var index = 0; index < this.scenes.length; index++) {
  11680. var scene = this.scenes[index];
  11681. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11682. var cam = scene.cameras[camIndex];
  11683. cam._currentRenderId = 0;
  11684. }
  11685. }
  11686. if (this.onResizeObservable.hasObservers) {
  11687. this.onResizeObservable.notifyObservers(this);
  11688. }
  11689. };
  11690. // WebVR functions
  11691. Engine.prototype.isVRDevicePresent = function () {
  11692. return !!this._vrDisplay;
  11693. };
  11694. Engine.prototype.getVRDevice = function () {
  11695. return this._vrDisplay;
  11696. };
  11697. /**
  11698. * Initializes a webVR display and starts listening to display change events.
  11699. * The onVRDisplayChangedObservable will be notified upon these changes.
  11700. * @returns The onVRDisplayChangedObservable.
  11701. */
  11702. Engine.prototype.initWebVR = function () {
  11703. this.initWebVRAsync();
  11704. return this.onVRDisplayChangedObservable;
  11705. };
  11706. /**
  11707. * Initializes a webVR display and starts listening to display change events.
  11708. * The onVRDisplayChangedObservable will be notified upon these changes.
  11709. * @returns A promise containing a VRDisplay and if vr is supported.
  11710. */
  11711. Engine.prototype.initWebVRAsync = function () {
  11712. var _this = this;
  11713. var notifyObservers = function () {
  11714. var eventArgs = {
  11715. vrDisplay: _this._vrDisplay,
  11716. vrSupported: _this._vrSupported
  11717. };
  11718. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11719. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11720. };
  11721. if (!this._onVrDisplayConnect) {
  11722. this._onVrDisplayConnect = function (event) {
  11723. _this._vrDisplay = event.display;
  11724. notifyObservers();
  11725. };
  11726. this._onVrDisplayDisconnect = function () {
  11727. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11728. _this._vrDisplay = undefined;
  11729. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11730. notifyObservers();
  11731. };
  11732. this._onVrDisplayPresentChange = function () {
  11733. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11734. };
  11735. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11736. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11737. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11738. }
  11739. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11740. this._webVRInitPromise.then(notifyObservers);
  11741. return this._webVRInitPromise;
  11742. };
  11743. Engine.prototype.enableVR = function () {
  11744. var _this = this;
  11745. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11746. var onResolved = function () {
  11747. _this.onVRRequestPresentComplete.notifyObservers(true);
  11748. _this._onVRFullScreenTriggered();
  11749. };
  11750. var onRejected = function () {
  11751. _this.onVRRequestPresentComplete.notifyObservers(false);
  11752. };
  11753. this.onVRRequestPresentStart.notifyObservers(this);
  11754. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11755. }
  11756. };
  11757. Engine.prototype.disableVR = function () {
  11758. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11759. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11760. }
  11761. };
  11762. Engine.prototype._getVRDisplaysAsync = function () {
  11763. var _this = this;
  11764. return new Promise(function (res, rej) {
  11765. if (navigator.getVRDisplays) {
  11766. navigator.getVRDisplays().then(function (devices) {
  11767. _this._vrSupported = true;
  11768. // note that devices may actually be an empty array. This is fine;
  11769. // we expect this._vrDisplay to be undefined in this case.
  11770. _this._vrDisplay = devices[0];
  11771. res({
  11772. vrDisplay: _this._vrDisplay,
  11773. vrSupported: _this._vrSupported
  11774. });
  11775. });
  11776. }
  11777. else {
  11778. _this._vrDisplay = undefined;
  11779. _this._vrSupported = false;
  11780. res({
  11781. vrDisplay: _this._vrDisplay,
  11782. vrSupported: _this._vrSupported
  11783. });
  11784. }
  11785. });
  11786. };
  11787. /**
  11788. * Binds the frame buffer to the specified texture.
  11789. * @param texture The texture to render to or null for the default canvas
  11790. * @param faceIndex The face of the texture to render to in case of cube texture
  11791. * @param requiredWidth The width of the target to render to
  11792. * @param requiredHeight The height of the target to render to
  11793. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11794. * @param depthStencilTexture The depth stencil texture to use to render
  11795. */
  11796. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11797. if (this._currentRenderTarget) {
  11798. this.unBindFramebuffer(this._currentRenderTarget);
  11799. }
  11800. this._currentRenderTarget = texture;
  11801. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11802. var gl = this._gl;
  11803. if (texture.isCube) {
  11804. if (faceIndex === undefined) {
  11805. faceIndex = 0;
  11806. }
  11807. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11808. if (depthStencilTexture) {
  11809. if (depthStencilTexture._generateStencilBuffer) {
  11810. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11811. }
  11812. else {
  11813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11814. }
  11815. }
  11816. }
  11817. if (this._cachedViewport && !forceFullscreenViewport) {
  11818. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11819. }
  11820. else {
  11821. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11822. }
  11823. this.wipeCaches();
  11824. };
  11825. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11826. if (this._currentFramebuffer !== framebuffer) {
  11827. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11828. this._currentFramebuffer = framebuffer;
  11829. }
  11830. };
  11831. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11832. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11833. this._currentRenderTarget = null;
  11834. // If MSAA, we need to bitblt back to main texture
  11835. var gl = this._gl;
  11836. if (texture._MSAAFramebuffer) {
  11837. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11838. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11839. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11840. }
  11841. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11842. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11843. gl.generateMipmap(gl.TEXTURE_2D);
  11844. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11845. }
  11846. if (onBeforeUnbind) {
  11847. if (texture._MSAAFramebuffer) {
  11848. // Bind the correct framebuffer
  11849. this.bindUnboundFramebuffer(texture._framebuffer);
  11850. }
  11851. onBeforeUnbind();
  11852. }
  11853. this.bindUnboundFramebuffer(null);
  11854. };
  11855. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11856. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11857. this._currentRenderTarget = null;
  11858. // If MSAA, we need to bitblt back to main texture
  11859. var gl = this._gl;
  11860. if (textures[0]._MSAAFramebuffer) {
  11861. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11862. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11863. var attachments = textures[0]._attachments;
  11864. if (!attachments) {
  11865. attachments = new Array(textures.length);
  11866. textures[0]._attachments = attachments;
  11867. }
  11868. for (var i = 0; i < textures.length; i++) {
  11869. var texture = textures[i];
  11870. for (var j = 0; j < attachments.length; j++) {
  11871. attachments[j] = gl.NONE;
  11872. }
  11873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11874. gl.readBuffer(attachments[i]);
  11875. gl.drawBuffers(attachments);
  11876. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11877. }
  11878. for (var i = 0; i < attachments.length; i++) {
  11879. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11880. }
  11881. gl.drawBuffers(attachments);
  11882. }
  11883. for (var i = 0; i < textures.length; i++) {
  11884. var texture = textures[i];
  11885. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11886. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11887. gl.generateMipmap(gl.TEXTURE_2D);
  11888. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11889. }
  11890. }
  11891. if (onBeforeUnbind) {
  11892. if (textures[0]._MSAAFramebuffer) {
  11893. // Bind the correct framebuffer
  11894. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11895. }
  11896. onBeforeUnbind();
  11897. }
  11898. this.bindUnboundFramebuffer(null);
  11899. };
  11900. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11901. if (texture.generateMipMaps) {
  11902. var gl = this._gl;
  11903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11904. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11906. }
  11907. };
  11908. Engine.prototype.flushFramebuffer = function () {
  11909. this._gl.flush();
  11910. };
  11911. Engine.prototype.restoreDefaultFramebuffer = function () {
  11912. if (this._currentRenderTarget) {
  11913. this.unBindFramebuffer(this._currentRenderTarget);
  11914. }
  11915. else {
  11916. this.bindUnboundFramebuffer(null);
  11917. }
  11918. if (this._cachedViewport) {
  11919. this.setViewport(this._cachedViewport);
  11920. }
  11921. this.wipeCaches();
  11922. };
  11923. // UBOs
  11924. Engine.prototype.createUniformBuffer = function (elements) {
  11925. var ubo = this._gl.createBuffer();
  11926. if (!ubo) {
  11927. throw new Error("Unable to create uniform buffer");
  11928. }
  11929. this.bindUniformBuffer(ubo);
  11930. if (elements instanceof Float32Array) {
  11931. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11932. }
  11933. else {
  11934. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11935. }
  11936. this.bindUniformBuffer(null);
  11937. ubo.references = 1;
  11938. return ubo;
  11939. };
  11940. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11941. var ubo = this._gl.createBuffer();
  11942. if (!ubo) {
  11943. throw new Error("Unable to create dynamic uniform buffer");
  11944. }
  11945. this.bindUniformBuffer(ubo);
  11946. if (elements instanceof Float32Array) {
  11947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11948. }
  11949. else {
  11950. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11951. }
  11952. this.bindUniformBuffer(null);
  11953. ubo.references = 1;
  11954. return ubo;
  11955. };
  11956. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11957. this.bindUniformBuffer(uniformBuffer);
  11958. if (offset === undefined) {
  11959. offset = 0;
  11960. }
  11961. if (count === undefined) {
  11962. if (elements instanceof Float32Array) {
  11963. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11964. }
  11965. else {
  11966. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11967. }
  11968. }
  11969. else {
  11970. if (elements instanceof Float32Array) {
  11971. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11972. }
  11973. else {
  11974. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11975. }
  11976. }
  11977. this.bindUniformBuffer(null);
  11978. };
  11979. // VBOs
  11980. Engine.prototype._resetVertexBufferBinding = function () {
  11981. this.bindArrayBuffer(null);
  11982. this._cachedVertexBuffers = null;
  11983. };
  11984. Engine.prototype.createVertexBuffer = function (vertices) {
  11985. var vbo = this._gl.createBuffer();
  11986. if (!vbo) {
  11987. throw new Error("Unable to create vertex buffer");
  11988. }
  11989. this.bindArrayBuffer(vbo);
  11990. if (vertices instanceof Float32Array) {
  11991. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11992. }
  11993. else {
  11994. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11995. }
  11996. this._resetVertexBufferBinding();
  11997. vbo.references = 1;
  11998. return vbo;
  11999. };
  12000. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12001. var vbo = this._gl.createBuffer();
  12002. if (!vbo) {
  12003. throw new Error("Unable to create dynamic vertex buffer");
  12004. }
  12005. this.bindArrayBuffer(vbo);
  12006. if (vertices instanceof Float32Array) {
  12007. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12008. }
  12009. else {
  12010. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12011. }
  12012. this._resetVertexBufferBinding();
  12013. vbo.references = 1;
  12014. return vbo;
  12015. };
  12016. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12017. if (offset === void 0) { offset = 0; }
  12018. // Force cache update
  12019. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12020. this.bindIndexBuffer(indexBuffer);
  12021. var arrayBuffer;
  12022. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12023. arrayBuffer = indices;
  12024. }
  12025. else {
  12026. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12027. }
  12028. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12029. this._resetIndexBufferBinding();
  12030. };
  12031. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12032. this.bindArrayBuffer(vertexBuffer);
  12033. if (offset === undefined) {
  12034. offset = 0;
  12035. }
  12036. if (count === undefined) {
  12037. if (vertices instanceof Float32Array) {
  12038. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12039. }
  12040. else {
  12041. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12042. }
  12043. }
  12044. else {
  12045. if (vertices instanceof Float32Array) {
  12046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12047. }
  12048. else {
  12049. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12050. }
  12051. }
  12052. this._resetVertexBufferBinding();
  12053. };
  12054. Engine.prototype._resetIndexBufferBinding = function () {
  12055. this.bindIndexBuffer(null);
  12056. this._cachedIndexBuffer = null;
  12057. };
  12058. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12059. var vbo = this._gl.createBuffer();
  12060. if (!vbo) {
  12061. throw new Error("Unable to create index buffer");
  12062. }
  12063. this.bindIndexBuffer(vbo);
  12064. // Check for 32 bits indices
  12065. var arrayBuffer;
  12066. var need32Bits = false;
  12067. if (indices instanceof Uint16Array) {
  12068. arrayBuffer = indices;
  12069. }
  12070. else {
  12071. //check 32 bit support
  12072. if (this._caps.uintIndices) {
  12073. if (indices instanceof Uint32Array) {
  12074. arrayBuffer = indices;
  12075. need32Bits = true;
  12076. }
  12077. else {
  12078. //number[] or Int32Array, check if 32 bit is necessary
  12079. for (var index = 0; index < indices.length; index++) {
  12080. if (indices[index] > 65535) {
  12081. need32Bits = true;
  12082. break;
  12083. }
  12084. }
  12085. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12086. }
  12087. }
  12088. else {
  12089. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12090. arrayBuffer = new Uint16Array(indices);
  12091. }
  12092. }
  12093. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12094. this._resetIndexBufferBinding();
  12095. vbo.references = 1;
  12096. vbo.is32Bits = need32Bits;
  12097. return vbo;
  12098. };
  12099. Engine.prototype.bindArrayBuffer = function (buffer) {
  12100. if (!this._vaoRecordInProgress) {
  12101. this._unbindVertexArrayObject();
  12102. }
  12103. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12104. };
  12105. Engine.prototype.bindUniformBuffer = function (buffer) {
  12106. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12107. };
  12108. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12109. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12110. };
  12111. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12112. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12113. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12114. };
  12115. ;
  12116. Engine.prototype.bindIndexBuffer = function (buffer) {
  12117. if (!this._vaoRecordInProgress) {
  12118. this._unbindVertexArrayObject();
  12119. }
  12120. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12121. };
  12122. Engine.prototype.bindBuffer = function (buffer, target) {
  12123. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12124. this._gl.bindBuffer(target, buffer);
  12125. this._currentBoundBuffer[target] = buffer;
  12126. }
  12127. };
  12128. Engine.prototype.updateArrayBuffer = function (data) {
  12129. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12130. };
  12131. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12132. var pointer = this._currentBufferPointers[indx];
  12133. var changed = false;
  12134. if (!pointer.active) {
  12135. changed = true;
  12136. pointer.active = true;
  12137. pointer.index = indx;
  12138. pointer.size = size;
  12139. pointer.type = type;
  12140. pointer.normalized = normalized;
  12141. pointer.stride = stride;
  12142. pointer.offset = offset;
  12143. pointer.buffer = buffer;
  12144. }
  12145. else {
  12146. if (pointer.buffer !== buffer) {
  12147. pointer.buffer = buffer;
  12148. changed = true;
  12149. }
  12150. if (pointer.size !== size) {
  12151. pointer.size = size;
  12152. changed = true;
  12153. }
  12154. if (pointer.type !== type) {
  12155. pointer.type = type;
  12156. changed = true;
  12157. }
  12158. if (pointer.normalized !== normalized) {
  12159. pointer.normalized = normalized;
  12160. changed = true;
  12161. }
  12162. if (pointer.stride !== stride) {
  12163. pointer.stride = stride;
  12164. changed = true;
  12165. }
  12166. if (pointer.offset !== offset) {
  12167. pointer.offset = offset;
  12168. changed = true;
  12169. }
  12170. }
  12171. if (changed || this._vaoRecordInProgress) {
  12172. this.bindArrayBuffer(buffer);
  12173. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12174. }
  12175. };
  12176. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12177. if (indexBuffer == null) {
  12178. return;
  12179. }
  12180. if (this._cachedIndexBuffer !== indexBuffer) {
  12181. this._cachedIndexBuffer = indexBuffer;
  12182. this.bindIndexBuffer(indexBuffer);
  12183. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12184. }
  12185. };
  12186. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12187. var attributes = effect.getAttributesNames();
  12188. if (!this._vaoRecordInProgress) {
  12189. this._unbindVertexArrayObject();
  12190. }
  12191. this.unbindAllAttributes();
  12192. for (var index = 0; index < attributes.length; index++) {
  12193. var order = effect.getAttributeLocation(index);
  12194. if (order >= 0) {
  12195. var vertexBuffer = vertexBuffers[attributes[index]];
  12196. if (!vertexBuffer) {
  12197. continue;
  12198. }
  12199. this._gl.enableVertexAttribArray(order);
  12200. if (!this._vaoRecordInProgress) {
  12201. this._vertexAttribArraysEnabled[order] = true;
  12202. }
  12203. var buffer = vertexBuffer.getBuffer();
  12204. if (buffer) {
  12205. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12206. if (vertexBuffer.getIsInstanced()) {
  12207. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12208. if (!this._vaoRecordInProgress) {
  12209. this._currentInstanceLocations.push(order);
  12210. this._currentInstanceBuffers.push(buffer);
  12211. }
  12212. }
  12213. }
  12214. }
  12215. }
  12216. };
  12217. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12218. var vao = this._gl.createVertexArray();
  12219. this._vaoRecordInProgress = true;
  12220. this._gl.bindVertexArray(vao);
  12221. this._mustWipeVertexAttributes = true;
  12222. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12223. this.bindIndexBuffer(indexBuffer);
  12224. this._vaoRecordInProgress = false;
  12225. this._gl.bindVertexArray(null);
  12226. return vao;
  12227. };
  12228. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12229. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12230. this._cachedVertexArrayObject = vertexArrayObject;
  12231. this._gl.bindVertexArray(vertexArrayObject);
  12232. this._cachedVertexBuffers = null;
  12233. this._cachedIndexBuffer = null;
  12234. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12235. this._mustWipeVertexAttributes = true;
  12236. }
  12237. };
  12238. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12239. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12240. this._cachedVertexBuffers = vertexBuffer;
  12241. this._cachedEffectForVertexBuffers = effect;
  12242. var attributesCount = effect.getAttributesCount();
  12243. this._unbindVertexArrayObject();
  12244. this.unbindAllAttributes();
  12245. var offset = 0;
  12246. for (var index = 0; index < attributesCount; index++) {
  12247. if (index < vertexDeclaration.length) {
  12248. var order = effect.getAttributeLocation(index);
  12249. if (order >= 0) {
  12250. this._gl.enableVertexAttribArray(order);
  12251. this._vertexAttribArraysEnabled[order] = true;
  12252. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12253. }
  12254. offset += vertexDeclaration[index] * 4;
  12255. }
  12256. }
  12257. }
  12258. this._bindIndexBufferWithCache(indexBuffer);
  12259. };
  12260. Engine.prototype._unbindVertexArrayObject = function () {
  12261. if (!this._cachedVertexArrayObject) {
  12262. return;
  12263. }
  12264. this._cachedVertexArrayObject = null;
  12265. this._gl.bindVertexArray(null);
  12266. };
  12267. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12268. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12269. this._cachedVertexBuffers = vertexBuffers;
  12270. this._cachedEffectForVertexBuffers = effect;
  12271. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12272. }
  12273. this._bindIndexBufferWithCache(indexBuffer);
  12274. };
  12275. Engine.prototype.unbindInstanceAttributes = function () {
  12276. var boundBuffer;
  12277. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12278. var instancesBuffer = this._currentInstanceBuffers[i];
  12279. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12280. boundBuffer = instancesBuffer;
  12281. this.bindArrayBuffer(instancesBuffer);
  12282. }
  12283. var offsetLocation = this._currentInstanceLocations[i];
  12284. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12285. }
  12286. this._currentInstanceBuffers.length = 0;
  12287. this._currentInstanceLocations.length = 0;
  12288. };
  12289. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12290. this._gl.deleteVertexArray(vao);
  12291. };
  12292. Engine.prototype._releaseBuffer = function (buffer) {
  12293. buffer.references--;
  12294. if (buffer.references === 0) {
  12295. this._gl.deleteBuffer(buffer);
  12296. return true;
  12297. }
  12298. return false;
  12299. };
  12300. Engine.prototype.createInstancesBuffer = function (capacity) {
  12301. var buffer = this._gl.createBuffer();
  12302. if (!buffer) {
  12303. throw new Error("Unable to create instance buffer");
  12304. }
  12305. buffer.capacity = capacity;
  12306. this.bindArrayBuffer(buffer);
  12307. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12308. return buffer;
  12309. };
  12310. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12311. this._gl.deleteBuffer(buffer);
  12312. };
  12313. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12314. this.bindArrayBuffer(instancesBuffer);
  12315. if (data) {
  12316. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12317. }
  12318. if (offsetLocations[0].index !== undefined) {
  12319. var stride = 0;
  12320. for (var i = 0; i < offsetLocations.length; i++) {
  12321. var ai = offsetLocations[i];
  12322. stride += ai.attributeSize * 4;
  12323. }
  12324. for (var i = 0; i < offsetLocations.length; i++) {
  12325. var ai = offsetLocations[i];
  12326. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12327. this._gl.enableVertexAttribArray(ai.index);
  12328. this._vertexAttribArraysEnabled[ai.index] = true;
  12329. }
  12330. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12331. this._gl.vertexAttribDivisor(ai.index, 1);
  12332. this._currentInstanceLocations.push(ai.index);
  12333. this._currentInstanceBuffers.push(instancesBuffer);
  12334. }
  12335. }
  12336. else {
  12337. for (var index = 0; index < 4; index++) {
  12338. var offsetLocation = offsetLocations[index];
  12339. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12340. this._gl.enableVertexAttribArray(offsetLocation);
  12341. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12342. }
  12343. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12344. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12345. this._currentInstanceLocations.push(offsetLocation);
  12346. this._currentInstanceBuffers.push(instancesBuffer);
  12347. }
  12348. }
  12349. };
  12350. Engine.prototype.applyStates = function () {
  12351. this._depthCullingState.apply(this._gl);
  12352. this._stencilState.apply(this._gl);
  12353. this._alphaState.apply(this._gl);
  12354. };
  12355. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12356. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12357. };
  12358. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12359. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12360. };
  12361. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12362. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12363. };
  12364. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12365. // Apply states
  12366. this.applyStates();
  12367. this._drawCalls.addCount(1, false);
  12368. // Render
  12369. var drawMode = this.DrawMode(fillMode);
  12370. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12371. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12372. if (instancesCount) {
  12373. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12374. }
  12375. else {
  12376. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12377. }
  12378. };
  12379. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12380. // Apply states
  12381. this.applyStates();
  12382. this._drawCalls.addCount(1, false);
  12383. var drawMode = this.DrawMode(fillMode);
  12384. if (instancesCount) {
  12385. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12386. }
  12387. else {
  12388. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12389. }
  12390. };
  12391. Engine.prototype.DrawMode = function (fillMode) {
  12392. switch (fillMode) {
  12393. // Triangle views
  12394. case BABYLON.Material.TriangleFillMode:
  12395. return this._gl.TRIANGLES;
  12396. case BABYLON.Material.PointFillMode:
  12397. return this._gl.POINTS;
  12398. case BABYLON.Material.WireFrameFillMode:
  12399. return this._gl.LINES;
  12400. // Draw modes
  12401. case BABYLON.Material.PointListDrawMode:
  12402. return this._gl.POINTS;
  12403. case BABYLON.Material.LineListDrawMode:
  12404. return this._gl.LINES;
  12405. case BABYLON.Material.LineLoopDrawMode:
  12406. return this._gl.LINE_LOOP;
  12407. case BABYLON.Material.LineStripDrawMode:
  12408. return this._gl.LINE_STRIP;
  12409. case BABYLON.Material.TriangleStripDrawMode:
  12410. return this._gl.TRIANGLE_STRIP;
  12411. case BABYLON.Material.TriangleFanDrawMode:
  12412. return this._gl.TRIANGLE_FAN;
  12413. default:
  12414. return this._gl.TRIANGLES;
  12415. }
  12416. };
  12417. // Shaders
  12418. Engine.prototype._releaseEffect = function (effect) {
  12419. if (this._compiledEffects[effect._key]) {
  12420. delete this._compiledEffects[effect._key];
  12421. this._deleteProgram(effect.getProgram());
  12422. }
  12423. };
  12424. Engine.prototype._deleteProgram = function (program) {
  12425. if (program) {
  12426. program.__SPECTOR_rebuildProgram = null;
  12427. if (program.transformFeedback) {
  12428. this.deleteTransformFeedback(program.transformFeedback);
  12429. program.transformFeedback = null;
  12430. }
  12431. this._gl.deleteProgram(program);
  12432. }
  12433. };
  12434. /**
  12435. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12436. * @param samplers An array of string used to represent textures
  12437. */
  12438. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12439. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12440. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12441. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12442. if (this._compiledEffects[name]) {
  12443. var compiledEffect = this._compiledEffects[name];
  12444. if (onCompiled && compiledEffect.isReady()) {
  12445. onCompiled(compiledEffect);
  12446. }
  12447. return compiledEffect;
  12448. }
  12449. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12450. effect._key = name;
  12451. this._compiledEffects[name] = effect;
  12452. return effect;
  12453. };
  12454. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12455. if (uniformsNames === void 0) { uniformsNames = []; }
  12456. if (samplers === void 0) { samplers = []; }
  12457. if (defines === void 0) { defines = ""; }
  12458. return this.createEffect({
  12459. vertex: "particles",
  12460. fragmentElement: fragmentName
  12461. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12462. };
  12463. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12464. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12465. context = context || this._gl;
  12466. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12467. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12468. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12469. };
  12470. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12471. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12472. context = context || this._gl;
  12473. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12474. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12475. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12476. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12477. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12478. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12479. return program;
  12480. };
  12481. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12482. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12483. var shaderProgram = context.createProgram();
  12484. if (!shaderProgram) {
  12485. throw new Error("Unable to create program");
  12486. }
  12487. context.attachShader(shaderProgram, vertexShader);
  12488. context.attachShader(shaderProgram, fragmentShader);
  12489. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12490. var transformFeedback = this.createTransformFeedback();
  12491. this.bindTransformFeedback(transformFeedback);
  12492. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12493. shaderProgram.transformFeedback = transformFeedback;
  12494. }
  12495. context.linkProgram(shaderProgram);
  12496. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12497. this.bindTransformFeedback(null);
  12498. }
  12499. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12500. if (!linked) {
  12501. context.validateProgram(shaderProgram);
  12502. var error = context.getProgramInfoLog(shaderProgram);
  12503. if (error) {
  12504. throw new Error(error);
  12505. }
  12506. }
  12507. context.deleteShader(vertexShader);
  12508. context.deleteShader(fragmentShader);
  12509. return shaderProgram;
  12510. };
  12511. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12512. var results = new Array();
  12513. for (var index = 0; index < uniformsNames.length; index++) {
  12514. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12515. }
  12516. return results;
  12517. };
  12518. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12519. var results = [];
  12520. for (var index = 0; index < attributesNames.length; index++) {
  12521. try {
  12522. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12523. }
  12524. catch (e) {
  12525. results.push(-1);
  12526. }
  12527. }
  12528. return results;
  12529. };
  12530. Engine.prototype.enableEffect = function (effect) {
  12531. if (!effect) {
  12532. return;
  12533. }
  12534. // Use program
  12535. this.bindSamplers(effect);
  12536. this._currentEffect = effect;
  12537. if (effect.onBind) {
  12538. effect.onBind(effect);
  12539. }
  12540. effect.onBindObservable.notifyObservers(effect);
  12541. };
  12542. Engine.prototype.setIntArray = function (uniform, array) {
  12543. if (!uniform)
  12544. return;
  12545. this._gl.uniform1iv(uniform, array);
  12546. };
  12547. Engine.prototype.setIntArray2 = function (uniform, array) {
  12548. if (!uniform || array.length % 2 !== 0)
  12549. return;
  12550. this._gl.uniform2iv(uniform, array);
  12551. };
  12552. Engine.prototype.setIntArray3 = function (uniform, array) {
  12553. if (!uniform || array.length % 3 !== 0)
  12554. return;
  12555. this._gl.uniform3iv(uniform, array);
  12556. };
  12557. Engine.prototype.setIntArray4 = function (uniform, array) {
  12558. if (!uniform || array.length % 4 !== 0)
  12559. return;
  12560. this._gl.uniform4iv(uniform, array);
  12561. };
  12562. Engine.prototype.setFloatArray = function (uniform, array) {
  12563. if (!uniform)
  12564. return;
  12565. this._gl.uniform1fv(uniform, array);
  12566. };
  12567. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12568. if (!uniform || array.length % 2 !== 0)
  12569. return;
  12570. this._gl.uniform2fv(uniform, array);
  12571. };
  12572. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12573. if (!uniform || array.length % 3 !== 0)
  12574. return;
  12575. this._gl.uniform3fv(uniform, array);
  12576. };
  12577. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12578. if (!uniform || array.length % 4 !== 0)
  12579. return;
  12580. this._gl.uniform4fv(uniform, array);
  12581. };
  12582. Engine.prototype.setArray = function (uniform, array) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniform1fv(uniform, array);
  12586. };
  12587. Engine.prototype.setArray2 = function (uniform, array) {
  12588. if (!uniform || array.length % 2 !== 0)
  12589. return;
  12590. this._gl.uniform2fv(uniform, array);
  12591. };
  12592. Engine.prototype.setArray3 = function (uniform, array) {
  12593. if (!uniform || array.length % 3 !== 0)
  12594. return;
  12595. this._gl.uniform3fv(uniform, array);
  12596. };
  12597. Engine.prototype.setArray4 = function (uniform, array) {
  12598. if (!uniform || array.length % 4 !== 0)
  12599. return;
  12600. this._gl.uniform4fv(uniform, array);
  12601. };
  12602. Engine.prototype.setMatrices = function (uniform, matrices) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12606. };
  12607. Engine.prototype.setMatrix = function (uniform, matrix) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12611. };
  12612. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12616. };
  12617. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12621. };
  12622. Engine.prototype.setInt = function (uniform, value) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform1i(uniform, value);
  12626. };
  12627. Engine.prototype.setFloat = function (uniform, value) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform1f(uniform, value);
  12631. };
  12632. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12633. if (!uniform)
  12634. return;
  12635. this._gl.uniform2f(uniform, x, y);
  12636. };
  12637. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12638. if (!uniform)
  12639. return;
  12640. this._gl.uniform3f(uniform, x, y, z);
  12641. };
  12642. Engine.prototype.setBool = function (uniform, bool) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniform1i(uniform, bool);
  12646. };
  12647. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12648. if (!uniform)
  12649. return;
  12650. this._gl.uniform4f(uniform, x, y, z, w);
  12651. };
  12652. Engine.prototype.setColor3 = function (uniform, color3) {
  12653. if (!uniform)
  12654. return;
  12655. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12656. };
  12657. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12658. if (!uniform)
  12659. return;
  12660. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12661. };
  12662. /**
  12663. * Sets a Color4 on a uniform variable
  12664. * @param uniform defines the uniform location
  12665. * @param color4 defines the value to be set
  12666. */
  12667. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12668. if (!uniform)
  12669. return;
  12670. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12671. };
  12672. // States
  12673. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12674. if (zOffset === void 0) { zOffset = 0; }
  12675. if (reverseSide === void 0) { reverseSide = false; }
  12676. // Culling
  12677. if (this._depthCullingState.cull !== culling || force) {
  12678. this._depthCullingState.cull = culling;
  12679. }
  12680. // Cull face
  12681. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12682. if (this._depthCullingState.cullFace !== cullFace || force) {
  12683. this._depthCullingState.cullFace = cullFace;
  12684. }
  12685. // Z offset
  12686. this.setZOffset(zOffset);
  12687. // Front face
  12688. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12689. if (this._depthCullingState.frontFace !== frontFace || force) {
  12690. this._depthCullingState.frontFace = frontFace;
  12691. }
  12692. };
  12693. Engine.prototype.setZOffset = function (value) {
  12694. this._depthCullingState.zOffset = value;
  12695. };
  12696. Engine.prototype.getZOffset = function () {
  12697. return this._depthCullingState.zOffset;
  12698. };
  12699. Engine.prototype.setDepthBuffer = function (enable) {
  12700. this._depthCullingState.depthTest = enable;
  12701. };
  12702. Engine.prototype.getDepthWrite = function () {
  12703. return this._depthCullingState.depthMask;
  12704. };
  12705. Engine.prototype.setDepthWrite = function (enable) {
  12706. this._depthCullingState.depthMask = enable;
  12707. };
  12708. Engine.prototype.setColorWrite = function (enable) {
  12709. this._gl.colorMask(enable, enable, enable, enable);
  12710. this._colorWrite = enable;
  12711. };
  12712. Engine.prototype.getColorWrite = function () {
  12713. return this._colorWrite;
  12714. };
  12715. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12716. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12717. };
  12718. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12719. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12720. if (this._alphaMode === mode) {
  12721. return;
  12722. }
  12723. switch (mode) {
  12724. case Engine.ALPHA_DISABLE:
  12725. this._alphaState.alphaBlend = false;
  12726. break;
  12727. case Engine.ALPHA_PREMULTIPLIED:
  12728. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12729. this._alphaState.alphaBlend = true;
  12730. break;
  12731. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12732. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12733. this._alphaState.alphaBlend = true;
  12734. break;
  12735. case Engine.ALPHA_COMBINE:
  12736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12737. this._alphaState.alphaBlend = true;
  12738. break;
  12739. case Engine.ALPHA_ONEONE:
  12740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12741. this._alphaState.alphaBlend = true;
  12742. break;
  12743. case Engine.ALPHA_ADD:
  12744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12745. this._alphaState.alphaBlend = true;
  12746. break;
  12747. case Engine.ALPHA_SUBTRACT:
  12748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12749. this._alphaState.alphaBlend = true;
  12750. break;
  12751. case Engine.ALPHA_MULTIPLY:
  12752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12753. this._alphaState.alphaBlend = true;
  12754. break;
  12755. case Engine.ALPHA_MAXIMIZED:
  12756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12757. this._alphaState.alphaBlend = true;
  12758. break;
  12759. case Engine.ALPHA_INTERPOLATE:
  12760. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12761. this._alphaState.alphaBlend = true;
  12762. break;
  12763. case Engine.ALPHA_SCREENMODE:
  12764. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12765. this._alphaState.alphaBlend = true;
  12766. break;
  12767. }
  12768. if (!noDepthWriteChange) {
  12769. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12770. }
  12771. this._alphaMode = mode;
  12772. };
  12773. Engine.prototype.getAlphaMode = function () {
  12774. return this._alphaMode;
  12775. };
  12776. // Textures
  12777. Engine.prototype.wipeCaches = function (bruteForce) {
  12778. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12779. return;
  12780. }
  12781. this._currentEffect = null;
  12782. // 6/8/2017: deltakosh: Should not be required anymore.
  12783. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12784. if (bruteForce) {
  12785. this.resetTextureCache();
  12786. this._currentProgram = null;
  12787. this._stencilState.reset();
  12788. this._depthCullingState.reset();
  12789. this.setDepthFunctionToLessOrEqual();
  12790. this._alphaState.reset();
  12791. }
  12792. this._resetVertexBufferBinding();
  12793. this._cachedIndexBuffer = null;
  12794. this._cachedEffectForVertexBuffers = null;
  12795. this._unbindVertexArrayObject();
  12796. this.bindIndexBuffer(null);
  12797. };
  12798. /**
  12799. * Set the compressed texture format to use, based on the formats you have, and the formats
  12800. * supported by the hardware / browser.
  12801. *
  12802. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12803. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12804. * to API arguments needed to compressed textures. This puts the burden on the container
  12805. * generator to house the arcane code for determining these for current & future formats.
  12806. *
  12807. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12808. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12809. *
  12810. * Note: The result of this call is not taken into account when a texture is base64.
  12811. *
  12812. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12813. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12814. *
  12815. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12816. * @returns The extension selected.
  12817. */
  12818. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12819. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12820. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12821. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12822. return this._textureFormatInUse = this._texturesSupported[i];
  12823. }
  12824. }
  12825. }
  12826. // actively set format to nothing, to allow this to be called more than once
  12827. // and possibly fail the 2nd time
  12828. this._textureFormatInUse = null;
  12829. return null;
  12830. };
  12831. Engine.prototype._createTexture = function () {
  12832. var texture = this._gl.createTexture();
  12833. if (!texture) {
  12834. throw new Error("Unable to create texture");
  12835. }
  12836. return texture;
  12837. };
  12838. /**
  12839. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12840. * @param {string} urlArg- This contains one of the following:
  12841. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12842. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12843. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12844. *
  12845. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12846. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12847. * @param {Scene} scene- Needed for loading to the correct scene.
  12848. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12849. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12850. * @param {callback} onError- Optional callback to be called upon failure.
  12851. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12852. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12853. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12854. *
  12855. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12856. */
  12857. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12858. var _this = this;
  12859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12860. if (onLoad === void 0) { onLoad = null; }
  12861. if (onError === void 0) { onError = null; }
  12862. if (buffer === void 0) { buffer = null; }
  12863. if (fallBack === void 0) { fallBack = null; }
  12864. if (format === void 0) { format = null; }
  12865. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12866. var fromData = url.substr(0, 5) === "data:";
  12867. var fromBlob = url.substr(0, 5) === "blob:";
  12868. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12869. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12870. // establish the file extension, if possible
  12871. var lastDot = url.lastIndexOf('.');
  12872. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12873. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12874. var isTGA = (extension.indexOf(".tga") === 0);
  12875. // determine if a ktx file should be substituted
  12876. var isKTX = false;
  12877. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12878. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12879. isKTX = true;
  12880. }
  12881. if (scene) {
  12882. scene._addPendingData(texture);
  12883. }
  12884. texture.url = url;
  12885. texture.generateMipMaps = !noMipmap;
  12886. texture.samplingMode = samplingMode;
  12887. texture.invertY = invertY;
  12888. if (!this._doNotHandleContextLost) {
  12889. // Keep a link to the buffer only if we plan to handle context lost
  12890. texture._buffer = buffer;
  12891. }
  12892. var onLoadObserver = null;
  12893. if (onLoad && !fallBack) {
  12894. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12895. }
  12896. if (!fallBack)
  12897. this._internalTexturesCache.push(texture);
  12898. var onerror = function (message, exception) {
  12899. if (scene) {
  12900. scene._removePendingData(texture);
  12901. }
  12902. if (onLoadObserver) {
  12903. texture.onLoadedObservable.remove(onLoadObserver);
  12904. }
  12905. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12906. if (isKTX) {
  12907. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12908. }
  12909. else if (BABYLON.Tools.UseFallbackTexture) {
  12910. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12911. }
  12912. if (onError) {
  12913. onError(message || "Unknown error", exception);
  12914. }
  12915. };
  12916. var callback = null;
  12917. // processing for non-image formats
  12918. if (isKTX || isTGA || isDDS) {
  12919. if (isKTX) {
  12920. callback = function (data) {
  12921. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12922. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12923. ktx.uploadLevels(_this._gl, !noMipmap);
  12924. return false;
  12925. }, samplingMode);
  12926. };
  12927. }
  12928. else if (isTGA) {
  12929. callback = function (arrayBuffer) {
  12930. var data = new Uint8Array(arrayBuffer);
  12931. var header = BABYLON.TGATools.GetTGAHeader(data);
  12932. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12933. BABYLON.TGATools.UploadContent(_this._gl, data);
  12934. return false;
  12935. }, samplingMode);
  12936. };
  12937. }
  12938. else if (isDDS) {
  12939. callback = function (data) {
  12940. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12942. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12943. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12944. return false;
  12945. }, samplingMode);
  12946. };
  12947. }
  12948. if (!buffer) {
  12949. this._loadFile(url, function (data) {
  12950. if (callback) {
  12951. callback(data);
  12952. }
  12953. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12954. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12955. });
  12956. }
  12957. else {
  12958. if (callback) {
  12959. callback(buffer);
  12960. }
  12961. }
  12962. // image format processing
  12963. }
  12964. else {
  12965. var onload = function (img) {
  12966. if (fromBlob && !_this._doNotHandleContextLost) {
  12967. // We need to store the image if we need to rebuild the texture
  12968. // in case of a webgl context lost
  12969. texture._buffer = img;
  12970. }
  12971. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12972. var gl = _this._gl;
  12973. var isPot = (img.width === potWidth && img.height === potHeight);
  12974. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12975. if (isPot) {
  12976. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12977. return false;
  12978. }
  12979. // Using shaders to rescale because canvas.drawImage is lossy
  12980. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12981. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12982. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12987. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12988. _this._releaseTexture(source);
  12989. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12990. continuationCallback();
  12991. });
  12992. return true;
  12993. }, samplingMode);
  12994. };
  12995. if (!fromData || isBase64)
  12996. if (buffer instanceof HTMLImageElement) {
  12997. onload(buffer);
  12998. }
  12999. else {
  13000. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13001. }
  13002. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13003. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13004. else
  13005. onload(buffer);
  13006. }
  13007. return texture;
  13008. };
  13009. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13010. var _this = this;
  13011. var rtt = this.createRenderTargetTexture({
  13012. width: destination.width,
  13013. height: destination.height,
  13014. }, {
  13015. generateMipMaps: false,
  13016. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13017. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13018. generateDepthBuffer: false,
  13019. generateStencilBuffer: false
  13020. });
  13021. if (!this._rescalePostProcess) {
  13022. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13023. }
  13024. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13025. _this._rescalePostProcess.onApply = function (effect) {
  13026. effect._bindTexture("textureSampler", source);
  13027. };
  13028. var hostingScene = scene;
  13029. if (!hostingScene) {
  13030. hostingScene = _this.scenes[_this.scenes.length - 1];
  13031. }
  13032. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13033. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13034. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13035. _this.unBindFramebuffer(rtt);
  13036. _this._releaseTexture(rtt);
  13037. if (onComplete) {
  13038. onComplete();
  13039. }
  13040. });
  13041. };
  13042. Engine.prototype._getInternalFormat = function (format) {
  13043. var internalFormat = this._gl.RGBA;
  13044. switch (format) {
  13045. case Engine.TEXTUREFORMAT_ALPHA:
  13046. internalFormat = this._gl.ALPHA;
  13047. break;
  13048. case Engine.TEXTUREFORMAT_LUMINANCE:
  13049. internalFormat = this._gl.LUMINANCE;
  13050. break;
  13051. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13052. internalFormat = this._gl.LUMINANCE_ALPHA;
  13053. break;
  13054. case Engine.TEXTUREFORMAT_RGB:
  13055. case Engine.TEXTUREFORMAT_RGB32F:
  13056. internalFormat = this._gl.RGB;
  13057. break;
  13058. case Engine.TEXTUREFORMAT_RGBA:
  13059. case Engine.TEXTUREFORMAT_RGBA32F:
  13060. internalFormat = this._gl.RGBA;
  13061. break;
  13062. case Engine.TEXTUREFORMAT_R32F:
  13063. internalFormat = this._gl.RED;
  13064. break;
  13065. case Engine.TEXTUREFORMAT_RG32F:
  13066. internalFormat = this._gl.RG;
  13067. break;
  13068. }
  13069. return internalFormat;
  13070. };
  13071. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13072. if (compression === void 0) { compression = null; }
  13073. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13074. if (!texture) {
  13075. return;
  13076. }
  13077. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13078. var internalFormat = this._getInternalFormat(format);
  13079. var textureType = this._getWebGLTextureType(type);
  13080. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13081. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13082. if (!this._doNotHandleContextLost) {
  13083. texture._bufferView = data;
  13084. texture.format = format;
  13085. texture.type = type;
  13086. texture.invertY = invertY;
  13087. texture._compression = compression;
  13088. }
  13089. if (texture.width % 4 !== 0) {
  13090. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13091. }
  13092. if (compression && data) {
  13093. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13094. }
  13095. else {
  13096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13097. }
  13098. if (texture.generateMipMaps) {
  13099. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13100. }
  13101. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13102. // this.resetTextureCache();
  13103. texture.isReady = true;
  13104. };
  13105. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13106. if (compression === void 0) { compression = null; }
  13107. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13108. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13109. texture.baseWidth = width;
  13110. texture.baseHeight = height;
  13111. texture.width = width;
  13112. texture.height = height;
  13113. texture.format = format;
  13114. texture.generateMipMaps = generateMipMaps;
  13115. texture.samplingMode = samplingMode;
  13116. texture.invertY = invertY;
  13117. texture._compression = compression;
  13118. texture.type = type;
  13119. if (!this._doNotHandleContextLost) {
  13120. texture._bufferView = data;
  13121. }
  13122. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13123. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13124. // Filters
  13125. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13128. if (generateMipMaps) {
  13129. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13130. }
  13131. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13132. this._internalTexturesCache.push(texture);
  13133. return texture;
  13134. };
  13135. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13136. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13137. texture.baseWidth = width;
  13138. texture.baseHeight = height;
  13139. if (generateMipMaps) {
  13140. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13141. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13142. }
  13143. // this.resetTextureCache();
  13144. texture.width = width;
  13145. texture.height = height;
  13146. texture.isReady = false;
  13147. texture.generateMipMaps = generateMipMaps;
  13148. texture.samplingMode = samplingMode;
  13149. this.updateTextureSamplingMode(samplingMode, texture);
  13150. this._internalTexturesCache.push(texture);
  13151. return texture;
  13152. };
  13153. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13154. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13155. if (texture.isCube) {
  13156. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13157. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13158. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13160. }
  13161. else if (texture.is3D) {
  13162. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13165. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13166. }
  13167. else {
  13168. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13170. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13171. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13172. }
  13173. texture.samplingMode = samplingMode;
  13174. };
  13175. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13176. if (premulAlpha === void 0) { premulAlpha = false; }
  13177. if (!texture) {
  13178. return;
  13179. }
  13180. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13181. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13182. if (premulAlpha) {
  13183. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13184. }
  13185. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13187. if (texture.generateMipMaps) {
  13188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13189. }
  13190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13191. if (premulAlpha) {
  13192. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13193. }
  13194. texture.isReady = true;
  13195. };
  13196. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13197. if (!texture || texture._isDisabled) {
  13198. return;
  13199. }
  13200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13201. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13202. try {
  13203. // Testing video texture support
  13204. if (this._videoTextureSupported === undefined) {
  13205. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13206. if (this._gl.getError() !== 0) {
  13207. this._videoTextureSupported = false;
  13208. }
  13209. else {
  13210. this._videoTextureSupported = true;
  13211. }
  13212. }
  13213. // Copy video through the current working canvas if video texture is not supported
  13214. if (!this._videoTextureSupported) {
  13215. if (!texture._workingCanvas) {
  13216. texture._workingCanvas = document.createElement("canvas");
  13217. var context = texture._workingCanvas.getContext("2d");
  13218. if (!context) {
  13219. throw new Error("Unable to get 2d context");
  13220. }
  13221. texture._workingContext = context;
  13222. texture._workingCanvas.width = texture.width;
  13223. texture._workingCanvas.height = texture.height;
  13224. }
  13225. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13227. }
  13228. else {
  13229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13230. }
  13231. if (texture.generateMipMaps) {
  13232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13233. }
  13234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13235. // this.resetTextureCache();
  13236. texture.isReady = true;
  13237. }
  13238. catch (ex) {
  13239. // Something unexpected
  13240. // Let's disable the texture
  13241. texture._isDisabled = true;
  13242. }
  13243. };
  13244. /**
  13245. * Updates a depth texture Comparison Mode and Function.
  13246. * If the comparison Function is equal to 0, the mode will be set to none.
  13247. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13248. * @param texture The texture to set the comparison function for
  13249. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13250. */
  13251. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13252. if (this.webGLVersion === 1) {
  13253. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13254. return;
  13255. }
  13256. var gl = this._gl;
  13257. if (texture.isCube) {
  13258. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13259. if (comparisonFunction === 0) {
  13260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13262. }
  13263. else {
  13264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13266. }
  13267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13268. }
  13269. else {
  13270. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13271. if (comparisonFunction === 0) {
  13272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13274. }
  13275. else {
  13276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13278. }
  13279. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13280. }
  13281. texture._comparisonFunction = comparisonFunction;
  13282. };
  13283. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13284. var width = size.width || size;
  13285. var height = size.height || size;
  13286. internalTexture.baseWidth = width;
  13287. internalTexture.baseHeight = height;
  13288. internalTexture.width = width;
  13289. internalTexture.height = height;
  13290. internalTexture.isReady = true;
  13291. internalTexture.samples = 1;
  13292. internalTexture.generateMipMaps = false;
  13293. internalTexture._generateDepthBuffer = true;
  13294. internalTexture._generateStencilBuffer = generateStencil;
  13295. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13296. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13297. internalTexture._comparisonFunction = comparisonFunction;
  13298. var gl = this._gl;
  13299. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13300. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13301. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13302. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13303. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13304. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13305. if (comparisonFunction === 0) {
  13306. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13307. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13308. }
  13309. else {
  13310. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13311. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13312. }
  13313. };
  13314. /**
  13315. * Creates a depth stencil texture.
  13316. * This is only available in WebGL 2 or with the depth texture extension available.
  13317. * @param size The size of face edge in the texture.
  13318. * @param options The options defining the texture.
  13319. * @returns The texture
  13320. */
  13321. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13322. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13323. if (!this._caps.depthTextureExtension) {
  13324. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13325. return internalTexture;
  13326. }
  13327. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13328. var gl = this._gl;
  13329. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13330. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13331. if (this.webGLVersion > 1) {
  13332. if (internalOptions.generateStencil) {
  13333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13334. }
  13335. else {
  13336. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13337. }
  13338. }
  13339. else {
  13340. if (internalOptions.generateStencil) {
  13341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13342. }
  13343. else {
  13344. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13345. }
  13346. }
  13347. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13348. return internalTexture;
  13349. };
  13350. /**
  13351. * Creates a depth stencil cube texture.
  13352. * This is only available in WebGL 2.
  13353. * @param size The size of face edge in the cube texture.
  13354. * @param options The options defining the cube texture.
  13355. * @returns The cube texture
  13356. */
  13357. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13358. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13359. internalTexture.isCube = true;
  13360. if (this.webGLVersion === 1) {
  13361. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13362. return internalTexture;
  13363. }
  13364. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13365. var gl = this._gl;
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13367. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13368. // Create the depth/stencil buffer
  13369. for (var face = 0; face < 6; face++) {
  13370. if (internalOptions.generateStencil) {
  13371. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13372. }
  13373. else {
  13374. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13375. }
  13376. }
  13377. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13378. return internalTexture;
  13379. };
  13380. /**
  13381. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13382. * @param renderTarget The render target to set the frame buffer for
  13383. */
  13384. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13385. // Create the framebuffer
  13386. var internalTexture = renderTarget.getInternalTexture();
  13387. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13388. return;
  13389. }
  13390. var gl = this._gl;
  13391. var depthStencilTexture = renderTarget.depthStencilTexture;
  13392. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13393. if (depthStencilTexture.isCube) {
  13394. if (depthStencilTexture._generateStencilBuffer) {
  13395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13396. }
  13397. else {
  13398. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13399. }
  13400. }
  13401. else {
  13402. if (depthStencilTexture._generateStencilBuffer) {
  13403. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13404. }
  13405. else {
  13406. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13407. }
  13408. }
  13409. this.bindUnboundFramebuffer(null);
  13410. };
  13411. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13412. var fullOptions = new RenderTargetCreationOptions();
  13413. if (options !== undefined && typeof options === "object") {
  13414. fullOptions.generateMipMaps = options.generateMipMaps;
  13415. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13416. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13417. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13418. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13419. }
  13420. else {
  13421. fullOptions.generateMipMaps = options;
  13422. fullOptions.generateDepthBuffer = true;
  13423. fullOptions.generateStencilBuffer = false;
  13424. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13425. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13426. }
  13427. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13428. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13429. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13430. }
  13431. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13432. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13433. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13434. }
  13435. var gl = this._gl;
  13436. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13437. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13438. var width = size.width || size;
  13439. var height = size.height || size;
  13440. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13441. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13442. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13443. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13444. }
  13445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13449. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13450. // Create the framebuffer
  13451. var framebuffer = gl.createFramebuffer();
  13452. this.bindUnboundFramebuffer(framebuffer);
  13453. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13454. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13455. if (fullOptions.generateMipMaps) {
  13456. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13457. }
  13458. // Unbind
  13459. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13461. this.bindUnboundFramebuffer(null);
  13462. texture._framebuffer = framebuffer;
  13463. texture.baseWidth = width;
  13464. texture.baseHeight = height;
  13465. texture.width = width;
  13466. texture.height = height;
  13467. texture.isReady = true;
  13468. texture.samples = 1;
  13469. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13470. texture.samplingMode = fullOptions.samplingMode;
  13471. texture.type = fullOptions.type;
  13472. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13473. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13474. // this.resetTextureCache();
  13475. this._internalTexturesCache.push(texture);
  13476. return texture;
  13477. };
  13478. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13479. var generateMipMaps = false;
  13480. var generateDepthBuffer = true;
  13481. var generateStencilBuffer = false;
  13482. var generateDepthTexture = false;
  13483. var textureCount = 1;
  13484. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13485. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13486. var types = [], samplingModes = [];
  13487. if (options !== undefined) {
  13488. generateMipMaps = options.generateMipMaps;
  13489. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13490. generateStencilBuffer = options.generateStencilBuffer;
  13491. generateDepthTexture = options.generateDepthTexture;
  13492. textureCount = options.textureCount || 1;
  13493. if (options.types) {
  13494. types = options.types;
  13495. }
  13496. if (options.samplingModes) {
  13497. samplingModes = options.samplingModes;
  13498. }
  13499. }
  13500. var gl = this._gl;
  13501. // Create the framebuffer
  13502. var framebuffer = gl.createFramebuffer();
  13503. this.bindUnboundFramebuffer(framebuffer);
  13504. var width = size.width || size;
  13505. var height = size.height || size;
  13506. var textures = [];
  13507. var attachments = [];
  13508. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13509. for (var i = 0; i < textureCount; i++) {
  13510. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13511. var type = types[i] || defaultType;
  13512. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13513. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13514. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13515. }
  13516. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13517. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13518. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13519. }
  13520. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13521. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13522. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13523. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13524. }
  13525. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13526. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13527. textures.push(texture);
  13528. attachments.push(attachment);
  13529. gl.activeTexture(gl["TEXTURE" + i]);
  13530. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13535. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13536. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13537. if (generateMipMaps) {
  13538. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13539. }
  13540. // Unbind
  13541. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13542. texture._framebuffer = framebuffer;
  13543. texture._depthStencilBuffer = depthStencilBuffer;
  13544. texture.baseWidth = width;
  13545. texture.baseHeight = height;
  13546. texture.width = width;
  13547. texture.height = height;
  13548. texture.isReady = true;
  13549. texture.samples = 1;
  13550. texture.generateMipMaps = generateMipMaps;
  13551. texture.samplingMode = samplingMode;
  13552. texture.type = type;
  13553. texture._generateDepthBuffer = generateDepthBuffer;
  13554. texture._generateStencilBuffer = generateStencilBuffer;
  13555. texture._attachments = attachments;
  13556. this._internalTexturesCache.push(texture);
  13557. }
  13558. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13559. // Depth texture
  13560. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13561. gl.activeTexture(gl.TEXTURE0);
  13562. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13567. 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);
  13568. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13569. depthTexture._framebuffer = framebuffer;
  13570. depthTexture.baseWidth = width;
  13571. depthTexture.baseHeight = height;
  13572. depthTexture.width = width;
  13573. depthTexture.height = height;
  13574. depthTexture.isReady = true;
  13575. depthTexture.samples = 1;
  13576. depthTexture.generateMipMaps = generateMipMaps;
  13577. depthTexture.samplingMode = gl.NEAREST;
  13578. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13579. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13580. textures.push(depthTexture);
  13581. this._internalTexturesCache.push(depthTexture);
  13582. }
  13583. gl.drawBuffers(attachments);
  13584. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13585. this.bindUnboundFramebuffer(null);
  13586. this.resetTextureCache();
  13587. return textures;
  13588. };
  13589. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13590. if (samples === void 0) { samples = 1; }
  13591. var depthStencilBuffer = null;
  13592. var gl = this._gl;
  13593. // Create the depth/stencil buffer
  13594. if (generateStencilBuffer) {
  13595. depthStencilBuffer = gl.createRenderbuffer();
  13596. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13597. if (samples > 1) {
  13598. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13599. }
  13600. else {
  13601. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13602. }
  13603. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13604. }
  13605. else if (generateDepthBuffer) {
  13606. depthStencilBuffer = gl.createRenderbuffer();
  13607. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13608. if (samples > 1) {
  13609. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13610. }
  13611. else {
  13612. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13613. }
  13614. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13615. }
  13616. return depthStencilBuffer;
  13617. };
  13618. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13619. if (this.webGLVersion < 2 || !texture) {
  13620. return 1;
  13621. }
  13622. if (texture.samples === samples) {
  13623. return samples;
  13624. }
  13625. var gl = this._gl;
  13626. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13627. // Dispose previous render buffers
  13628. if (texture._depthStencilBuffer) {
  13629. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13630. texture._depthStencilBuffer = null;
  13631. }
  13632. if (texture._MSAAFramebuffer) {
  13633. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13634. texture._MSAAFramebuffer = null;
  13635. }
  13636. if (texture._MSAARenderBuffer) {
  13637. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13638. texture._MSAARenderBuffer = null;
  13639. }
  13640. if (samples > 1) {
  13641. var framebuffer = gl.createFramebuffer();
  13642. if (!framebuffer) {
  13643. throw new Error("Unable to create multi sampled framebuffer");
  13644. }
  13645. texture._MSAAFramebuffer = framebuffer;
  13646. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13647. var colorRenderbuffer = gl.createRenderbuffer();
  13648. if (!colorRenderbuffer) {
  13649. throw new Error("Unable to create multi sampled framebuffer");
  13650. }
  13651. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13652. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13654. texture._MSAARenderBuffer = colorRenderbuffer;
  13655. }
  13656. else {
  13657. this.bindUnboundFramebuffer(texture._framebuffer);
  13658. }
  13659. texture.samples = samples;
  13660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. return samples;
  13664. };
  13665. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13666. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13667. return 1;
  13668. }
  13669. if (textures[0].samples === samples) {
  13670. return samples;
  13671. }
  13672. var gl = this._gl;
  13673. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13674. // Dispose previous render buffers
  13675. if (textures[0]._depthStencilBuffer) {
  13676. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13677. textures[0]._depthStencilBuffer = null;
  13678. }
  13679. if (textures[0]._MSAAFramebuffer) {
  13680. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13681. textures[0]._MSAAFramebuffer = null;
  13682. }
  13683. for (var i = 0; i < textures.length; i++) {
  13684. if (textures[i]._MSAARenderBuffer) {
  13685. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13686. textures[i]._MSAARenderBuffer = null;
  13687. }
  13688. }
  13689. if (samples > 1) {
  13690. var framebuffer = gl.createFramebuffer();
  13691. if (!framebuffer) {
  13692. throw new Error("Unable to create multi sampled framebuffer");
  13693. }
  13694. this.bindUnboundFramebuffer(framebuffer);
  13695. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13696. var attachments = [];
  13697. for (var i = 0; i < textures.length; i++) {
  13698. var texture = textures[i];
  13699. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13700. var colorRenderbuffer = gl.createRenderbuffer();
  13701. if (!colorRenderbuffer) {
  13702. throw new Error("Unable to create multi sampled framebuffer");
  13703. }
  13704. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13705. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13706. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13707. texture._MSAAFramebuffer = framebuffer;
  13708. texture._MSAARenderBuffer = colorRenderbuffer;
  13709. texture.samples = samples;
  13710. texture._depthStencilBuffer = depthStencilBuffer;
  13711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13712. attachments.push(attachment);
  13713. }
  13714. gl.drawBuffers(attachments);
  13715. }
  13716. else {
  13717. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13718. }
  13719. this.bindUnboundFramebuffer(null);
  13720. return samples;
  13721. };
  13722. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13723. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13724. };
  13725. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13726. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13727. };
  13728. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13729. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13730. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13731. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13732. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13733. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13734. }
  13735. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13736. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13737. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13738. }
  13739. var gl = this._gl;
  13740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13741. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13742. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13744. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13745. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13746. }
  13747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13751. for (var face = 0; face < 6; face++) {
  13752. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13753. }
  13754. // Create the framebuffer
  13755. var framebuffer = gl.createFramebuffer();
  13756. this.bindUnboundFramebuffer(framebuffer);
  13757. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13758. // MipMaps
  13759. if (fullOptions.generateMipMaps) {
  13760. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13761. }
  13762. // Unbind
  13763. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. texture._framebuffer = framebuffer;
  13767. texture.width = size;
  13768. texture.height = size;
  13769. texture.isReady = true;
  13770. texture.isCube = true;
  13771. texture.samples = 1;
  13772. texture.generateMipMaps = fullOptions.generateMipMaps;
  13773. texture.samplingMode = fullOptions.samplingMode;
  13774. texture.type = fullOptions.type;
  13775. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13776. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13777. this._internalTexturesCache.push(texture);
  13778. return texture;
  13779. };
  13780. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13781. var _this = this;
  13782. if (onLoad === void 0) { onLoad = null; }
  13783. if (onError === void 0) { onError = null; }
  13784. if (forcedExtension === void 0) { forcedExtension = null; }
  13785. var callback = function (loadData) {
  13786. if (!loadData) {
  13787. if (onLoad) {
  13788. onLoad(null);
  13789. }
  13790. return;
  13791. }
  13792. var texture = loadData.texture;
  13793. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13794. texture._lodGenerationScale = scale;
  13795. texture._lodGenerationOffset = offset;
  13796. if (_this._caps.textureLOD) {
  13797. // Do not add extra process if texture lod is supported.
  13798. if (onLoad) {
  13799. onLoad(texture);
  13800. }
  13801. return;
  13802. }
  13803. var mipSlices = 3;
  13804. var gl = _this._gl;
  13805. var width = loadData.width;
  13806. if (!width) {
  13807. return;
  13808. }
  13809. var textures = [];
  13810. for (var i = 0; i < mipSlices; i++) {
  13811. //compute LOD from even spacing in smoothness (matching shader calculation)
  13812. var smoothness = i / (mipSlices - 1);
  13813. var roughness = 1 - smoothness;
  13814. var minLODIndex = offset; // roughness = 0
  13815. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13816. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13817. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13818. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13819. glTextureFromLod.isCube = true;
  13820. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13825. if (loadData.isDDS) {
  13826. var info = loadData.info;
  13827. var data = loadData.data;
  13828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13829. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13830. }
  13831. else {
  13832. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13833. }
  13834. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13835. // Wrap in a base texture for easy binding.
  13836. var lodTexture = new BABYLON.BaseTexture(scene);
  13837. lodTexture.isCube = true;
  13838. lodTexture._texture = glTextureFromLod;
  13839. glTextureFromLod.isReady = true;
  13840. textures.push(lodTexture);
  13841. }
  13842. texture._lodTextureHigh = textures[2];
  13843. texture._lodTextureMid = textures[1];
  13844. texture._lodTextureLow = textures[0];
  13845. if (onLoad) {
  13846. onLoad(texture);
  13847. }
  13848. };
  13849. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13850. };
  13851. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13852. var _this = this;
  13853. if (onLoad === void 0) { onLoad = null; }
  13854. if (onError === void 0) { onError = null; }
  13855. if (forcedExtension === void 0) { forcedExtension = null; }
  13856. var gl = this._gl;
  13857. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13858. texture.isCube = true;
  13859. texture.url = rootUrl;
  13860. texture.generateMipMaps = !noMipmap;
  13861. if (!this._doNotHandleContextLost) {
  13862. texture._extension = forcedExtension;
  13863. texture._files = files;
  13864. }
  13865. var isKTX = false;
  13866. var isDDS = false;
  13867. var lastDot = rootUrl.lastIndexOf('.');
  13868. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13869. if (this._textureFormatInUse) {
  13870. extension = this._textureFormatInUse;
  13871. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13872. isKTX = true;
  13873. }
  13874. else {
  13875. isDDS = (extension === ".dds");
  13876. }
  13877. var onerror = function (request, exception) {
  13878. if (onError && request) {
  13879. onError(request.status + " " + request.statusText, exception);
  13880. }
  13881. };
  13882. if (isKTX) {
  13883. this._loadFile(rootUrl, function (data) {
  13884. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13885. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13888. ktx.uploadLevels(_this._gl, !noMipmap);
  13889. _this.setCubeMapTextureParams(gl, loadMipmap);
  13890. texture.width = ktx.pixelWidth;
  13891. texture.height = ktx.pixelHeight;
  13892. texture.isReady = true;
  13893. }, undefined, undefined, true, onerror);
  13894. }
  13895. else if (isDDS) {
  13896. if (files && files.length === 6) {
  13897. this._cascadeLoadFiles(scene, function (imgs) {
  13898. var info;
  13899. var loadMipmap = false;
  13900. var width = 0;
  13901. for (var index = 0; index < imgs.length; index++) {
  13902. var data = imgs[index];
  13903. info = BABYLON.DDSTools.GetDDSInfo(data);
  13904. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13907. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13908. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13910. }
  13911. texture.width = info.width;
  13912. texture.height = info.height;
  13913. texture.type = info.textureType;
  13914. width = info.width;
  13915. }
  13916. _this.setCubeMapTextureParams(gl, loadMipmap);
  13917. texture.isReady = true;
  13918. if (onLoad) {
  13919. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13920. }
  13921. }, files, onError);
  13922. }
  13923. else {
  13924. this._loadFile(rootUrl, function (data) {
  13925. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13926. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13927. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13929. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13930. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13932. }
  13933. _this.setCubeMapTextureParams(gl, loadMipmap);
  13934. texture.width = info.width;
  13935. texture.height = info.height;
  13936. texture.isReady = true;
  13937. texture.type = info.textureType;
  13938. if (onLoad) {
  13939. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13940. }
  13941. }, undefined, undefined, true, onerror);
  13942. }
  13943. }
  13944. else {
  13945. if (!files) {
  13946. throw new Error("Cannot load cubemap because files were not defined");
  13947. }
  13948. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13949. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13950. var height = width;
  13951. _this._prepareWorkingCanvas();
  13952. if (!_this._workingCanvas || !_this._workingContext) {
  13953. return;
  13954. }
  13955. _this._workingCanvas.width = width;
  13956. _this._workingCanvas.height = height;
  13957. var faces = [
  13958. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13959. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13960. ];
  13961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13963. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13964. for (var index = 0; index < faces.length; index++) {
  13965. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13966. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13967. }
  13968. if (!noMipmap) {
  13969. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13970. }
  13971. _this.setCubeMapTextureParams(gl, !noMipmap);
  13972. texture.width = width;
  13973. texture.height = height;
  13974. texture.isReady = true;
  13975. if (format) {
  13976. texture.format = format;
  13977. }
  13978. texture.onLoadedObservable.notifyObservers(texture);
  13979. texture.onLoadedObservable.clear();
  13980. if (onLoad) {
  13981. onLoad();
  13982. }
  13983. }, files, onError);
  13984. }
  13985. this._internalTexturesCache.push(texture);
  13986. return texture;
  13987. };
  13988. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13991. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13993. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13994. // this.resetTextureCache();
  13995. };
  13996. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13997. if (compression === void 0) { compression = null; }
  13998. if (level === void 0) { level = 0; }
  13999. texture._bufferViewArray = data;
  14000. texture.format = format;
  14001. texture.type = type;
  14002. texture.invertY = invertY;
  14003. texture._compression = compression;
  14004. var gl = this._gl;
  14005. var textureType = this._getWebGLTextureType(type);
  14006. var internalFormat = this._getInternalFormat(format);
  14007. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14008. var needConversion = false;
  14009. if (internalFormat === gl.RGB) {
  14010. internalFormat = gl.RGBA;
  14011. needConversion = true;
  14012. }
  14013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14014. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14015. if (texture.width % 4 !== 0) {
  14016. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14017. }
  14018. // Data are known to be in +X +Y +Z -X -Y -Z
  14019. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14020. var faceData = data[faceIndex];
  14021. if (compression) {
  14022. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14023. }
  14024. else {
  14025. if (needConversion) {
  14026. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14027. }
  14028. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14029. }
  14030. }
  14031. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14032. if (isPot && texture.generateMipMaps && level === 0) {
  14033. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14034. }
  14035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14036. // this.resetTextureCache();
  14037. texture.isReady = true;
  14038. };
  14039. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14040. if (compression === void 0) { compression = null; }
  14041. var gl = this._gl;
  14042. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14043. texture.isCube = true;
  14044. texture.generateMipMaps = generateMipMaps;
  14045. texture.format = format;
  14046. texture.type = type;
  14047. if (!this._doNotHandleContextLost) {
  14048. texture._bufferViewArray = data;
  14049. }
  14050. var textureType = this._getWebGLTextureType(type);
  14051. var internalFormat = this._getInternalFormat(format);
  14052. if (internalFormat === gl.RGB) {
  14053. internalFormat = gl.RGBA;
  14054. }
  14055. var width = size;
  14056. var height = width;
  14057. texture.width = width;
  14058. texture.height = height;
  14059. // Double check on POT to generate Mips.
  14060. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14061. if (!isPot) {
  14062. generateMipMaps = false;
  14063. }
  14064. // Upload data if needed. The texture won't be ready until then.
  14065. if (data) {
  14066. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14067. }
  14068. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14069. // Filters
  14070. if (data && generateMipMaps) {
  14071. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14072. }
  14073. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14076. }
  14077. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14080. }
  14081. else {
  14082. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14085. }
  14086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14088. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14089. return texture;
  14090. };
  14091. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14092. var _this = this;
  14093. if (onLoad === void 0) { onLoad = null; }
  14094. if (onError === void 0) { onError = null; }
  14095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14096. if (invertY === void 0) { invertY = false; }
  14097. var gl = this._gl;
  14098. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14099. scene._addPendingData(texture);
  14100. texture.url = url;
  14101. this._internalTexturesCache.push(texture);
  14102. var onerror = function (request, exception) {
  14103. scene._removePendingData(texture);
  14104. if (onError && request) {
  14105. onError(request.status + " " + request.statusText, exception);
  14106. }
  14107. };
  14108. var internalCallback = function (data) {
  14109. var width = texture.width;
  14110. var faceDataArrays = callback(data);
  14111. if (!faceDataArrays) {
  14112. return;
  14113. }
  14114. if (mipmmapGenerator) {
  14115. var textureType = _this._getWebGLTextureType(type);
  14116. var internalFormat = _this._getInternalFormat(format);
  14117. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14118. var needConversion = false;
  14119. if (internalFormat === gl.RGB) {
  14120. internalFormat = gl.RGBA;
  14121. needConversion = true;
  14122. }
  14123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14124. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14125. var mipData = mipmmapGenerator(faceDataArrays);
  14126. for (var level = 0; level < mipData.length; level++) {
  14127. var mipSize = width >> level;
  14128. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14129. var mipFaceData = mipData[level][faceIndex];
  14130. if (needConversion) {
  14131. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14132. }
  14133. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14134. }
  14135. }
  14136. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14137. }
  14138. else {
  14139. texture.generateMipMaps = !noMipmap;
  14140. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14141. }
  14142. texture.isReady = true;
  14143. // this.resetTextureCache();
  14144. scene._removePendingData(texture);
  14145. if (onLoad) {
  14146. onLoad();
  14147. }
  14148. };
  14149. this._loadFile(url, function (data) {
  14150. internalCallback(data);
  14151. }, undefined, scene.database, true, onerror);
  14152. return texture;
  14153. };
  14154. ;
  14155. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14156. if (compression === void 0) { compression = null; }
  14157. var internalFormat = this._getInternalFormat(format);
  14158. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14160. if (!this._doNotHandleContextLost) {
  14161. texture._bufferView = data;
  14162. texture.format = format;
  14163. texture.invertY = invertY;
  14164. texture._compression = compression;
  14165. }
  14166. if (texture.width % 4 !== 0) {
  14167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14168. }
  14169. if (compression && data) {
  14170. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14171. }
  14172. else {
  14173. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14174. }
  14175. if (texture.generateMipMaps) {
  14176. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14177. }
  14178. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14179. // this.resetTextureCache();
  14180. texture.isReady = true;
  14181. };
  14182. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14183. if (compression === void 0) { compression = null; }
  14184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14185. texture.baseWidth = width;
  14186. texture.baseHeight = height;
  14187. texture.baseDepth = depth;
  14188. texture.width = width;
  14189. texture.height = height;
  14190. texture.depth = depth;
  14191. texture.format = format;
  14192. texture.generateMipMaps = generateMipMaps;
  14193. texture.samplingMode = samplingMode;
  14194. texture.is3D = true;
  14195. if (!this._doNotHandleContextLost) {
  14196. texture._bufferView = data;
  14197. }
  14198. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14200. // Filters
  14201. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14204. if (generateMipMaps) {
  14205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14206. }
  14207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14208. this._internalTexturesCache.push(texture);
  14209. return texture;
  14210. };
  14211. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14212. var gl = this._gl;
  14213. if (!gl) {
  14214. return;
  14215. }
  14216. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14219. if (!noMipmap && !isCompressed) {
  14220. gl.generateMipmap(gl.TEXTURE_2D);
  14221. }
  14222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14223. // this.resetTextureCache();
  14224. if (scene) {
  14225. scene._removePendingData(texture);
  14226. }
  14227. texture.onLoadedObservable.notifyObservers(texture);
  14228. texture.onLoadedObservable.clear();
  14229. };
  14230. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14231. var _this = this;
  14232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14233. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14234. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14235. var gl = this._gl;
  14236. if (!gl) {
  14237. return;
  14238. }
  14239. if (!texture._webGLTexture) {
  14240. // this.resetTextureCache();
  14241. if (scene) {
  14242. scene._removePendingData(texture);
  14243. }
  14244. return;
  14245. }
  14246. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14248. texture.baseWidth = width;
  14249. texture.baseHeight = height;
  14250. texture.width = potWidth;
  14251. texture.height = potHeight;
  14252. texture.isReady = true;
  14253. if (processFunction(potWidth, potHeight, function () {
  14254. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14255. })) {
  14256. // Returning as texture needs extra async steps
  14257. return;
  14258. }
  14259. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14260. };
  14261. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14262. // Create new RGBA data container.
  14263. var rgbaData;
  14264. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14265. rgbaData = new Float32Array(width * height * 4);
  14266. }
  14267. else {
  14268. rgbaData = new Uint32Array(width * height * 4);
  14269. }
  14270. // Convert each pixel.
  14271. for (var x = 0; x < width; x++) {
  14272. for (var y = 0; y < height; y++) {
  14273. var index = (y * width + x) * 3;
  14274. var newIndex = (y * width + x) * 4;
  14275. // Map Old Value to new value.
  14276. rgbaData[newIndex + 0] = rgbData[index + 0];
  14277. rgbaData[newIndex + 1] = rgbData[index + 1];
  14278. rgbaData[newIndex + 2] = rgbData[index + 2];
  14279. // Add fully opaque alpha channel.
  14280. rgbaData[newIndex + 3] = 1;
  14281. }
  14282. }
  14283. return rgbaData;
  14284. };
  14285. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14286. var gl = this._gl;
  14287. if (texture._framebuffer) {
  14288. gl.deleteFramebuffer(texture._framebuffer);
  14289. texture._framebuffer = null;
  14290. }
  14291. if (texture._depthStencilBuffer) {
  14292. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14293. texture._depthStencilBuffer = null;
  14294. }
  14295. if (texture._MSAAFramebuffer) {
  14296. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14297. texture._MSAAFramebuffer = null;
  14298. }
  14299. if (texture._MSAARenderBuffer) {
  14300. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14301. texture._MSAARenderBuffer = null;
  14302. }
  14303. };
  14304. Engine.prototype._releaseTexture = function (texture) {
  14305. var gl = this._gl;
  14306. this._releaseFramebufferObjects(texture);
  14307. gl.deleteTexture(texture._webGLTexture);
  14308. // Unbind channels
  14309. this.unbindAllTextures();
  14310. var index = this._internalTexturesCache.indexOf(texture);
  14311. if (index !== -1) {
  14312. this._internalTexturesCache.splice(index, 1);
  14313. }
  14314. // Integrated fixed lod samplers.
  14315. if (texture._lodTextureHigh) {
  14316. texture._lodTextureHigh.dispose();
  14317. }
  14318. if (texture._lodTextureMid) {
  14319. texture._lodTextureMid.dispose();
  14320. }
  14321. if (texture._lodTextureLow) {
  14322. texture._lodTextureLow.dispose();
  14323. }
  14324. };
  14325. Engine.prototype.setProgram = function (program) {
  14326. if (this._currentProgram !== program) {
  14327. this._gl.useProgram(program);
  14328. this._currentProgram = program;
  14329. }
  14330. };
  14331. Engine.prototype.bindSamplers = function (effect) {
  14332. this.setProgram(effect.getProgram());
  14333. var samplers = effect.getSamplers();
  14334. for (var index = 0; index < samplers.length; index++) {
  14335. var uniform = effect.getUniform(samplers[index]);
  14336. if (uniform) {
  14337. this._boundUniforms[index] = uniform;
  14338. }
  14339. }
  14340. this._currentEffect = null;
  14341. };
  14342. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14343. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14344. return;
  14345. }
  14346. // Remove
  14347. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14348. // Bind last to it
  14349. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14350. // Bind to dummy
  14351. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14352. };
  14353. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14354. if (!internalTexture) {
  14355. return -1;
  14356. }
  14357. internalTexture._initialSlot = channel;
  14358. if (this.disableTextureBindingOptimization) {
  14359. if (channel !== internalTexture._designatedSlot) {
  14360. this._textureCollisions.addCount(1, false);
  14361. }
  14362. }
  14363. else {
  14364. if (channel !== internalTexture._designatedSlot) {
  14365. if (internalTexture._designatedSlot > -1) {
  14366. return internalTexture._designatedSlot;
  14367. }
  14368. else {
  14369. // No slot for this texture, let's pick a new one (if we find a free slot)
  14370. if (this._nextFreeTextureSlots.length) {
  14371. return this._nextFreeTextureSlots[0];
  14372. }
  14373. // We need to recycle the oldest bound texture, sorry.
  14374. this._textureCollisions.addCount(1, false);
  14375. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14376. }
  14377. }
  14378. }
  14379. return channel;
  14380. };
  14381. Engine.prototype._linkTrackers = function (previous, next) {
  14382. previous.next = next;
  14383. next.previous = previous;
  14384. };
  14385. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14386. var currentSlot = internalTexture._designatedSlot;
  14387. if (currentSlot === -1) {
  14388. return -1;
  14389. }
  14390. internalTexture._designatedSlot = -1;
  14391. if (this.disableTextureBindingOptimization) {
  14392. return -1;
  14393. }
  14394. // Remove from bound list
  14395. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14396. // Free the slot
  14397. this._boundTexturesCache[currentSlot] = null;
  14398. this._nextFreeTextureSlots.push(currentSlot);
  14399. return currentSlot;
  14400. };
  14401. Engine.prototype._activateCurrentTexture = function () {
  14402. if (this._currentTextureChannel !== this._activeChannel) {
  14403. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14404. this._currentTextureChannel = this._activeChannel;
  14405. }
  14406. };
  14407. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14408. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14409. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14410. this._activeChannel = texture._designatedSlot;
  14411. }
  14412. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14413. var isTextureForRendering = texture && texture._initialSlot > -1;
  14414. if (currentTextureBound !== texture) {
  14415. if (currentTextureBound) {
  14416. this._removeDesignatedSlot(currentTextureBound);
  14417. }
  14418. this._activateCurrentTexture();
  14419. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14420. this._boundTexturesCache[this._activeChannel] = texture;
  14421. if (texture) {
  14422. if (!this.disableTextureBindingOptimization) {
  14423. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14424. if (slotIndex > -1) {
  14425. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14426. }
  14427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14428. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14429. }
  14430. texture._designatedSlot = this._activeChannel;
  14431. }
  14432. }
  14433. else if (forTextureDataUpdate) {
  14434. this._activateCurrentTexture();
  14435. }
  14436. if (isTextureForRendering && !forTextureDataUpdate) {
  14437. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14438. }
  14439. };
  14440. Engine.prototype._bindTexture = function (channel, texture) {
  14441. if (channel < 0) {
  14442. return;
  14443. }
  14444. if (texture) {
  14445. channel = this._getCorrectTextureChannel(channel, texture);
  14446. }
  14447. this._activeChannel = channel;
  14448. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14449. };
  14450. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14451. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14452. };
  14453. Engine.prototype.unbindAllTextures = function () {
  14454. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14455. this._activeChannel = channel;
  14456. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14457. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14458. if (this.webGLVersion > 1) {
  14459. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14460. }
  14461. }
  14462. };
  14463. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14464. if (channel < 0) {
  14465. return;
  14466. }
  14467. if (uniform) {
  14468. this._boundUniforms[channel] = uniform;
  14469. }
  14470. this._setTexture(channel, texture);
  14471. };
  14472. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14473. var uniform = this._boundUniforms[sourceSlot];
  14474. if (uniform._currentState === destination) {
  14475. return;
  14476. }
  14477. this._gl.uniform1i(uniform, destination);
  14478. uniform._currentState = destination;
  14479. };
  14480. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14481. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14482. // Not ready?
  14483. if (!texture) {
  14484. if (this._boundTexturesCache[channel] != null) {
  14485. this._activeChannel = channel;
  14486. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14488. if (this.webGLVersion > 1) {
  14489. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14490. }
  14491. }
  14492. return false;
  14493. }
  14494. // Video
  14495. if (texture.video) {
  14496. this._activeChannel = channel;
  14497. texture.update();
  14498. }
  14499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14500. texture.delayLoad();
  14501. return false;
  14502. }
  14503. var internalTexture;
  14504. if (texture.isReady()) {
  14505. internalTexture = texture.getInternalTexture();
  14506. }
  14507. else if (texture.isCube) {
  14508. internalTexture = this.emptyCubeTexture;
  14509. }
  14510. else if (texture.is3D) {
  14511. internalTexture = this.emptyTexture3D;
  14512. }
  14513. else {
  14514. internalTexture = this.emptyTexture;
  14515. }
  14516. if (!isPartOfTextureArray) {
  14517. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14518. }
  14519. if (this._boundTexturesCache[channel] === internalTexture) {
  14520. this._moveBoundTextureOnTop(internalTexture);
  14521. if (!isPartOfTextureArray) {
  14522. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14523. }
  14524. return false;
  14525. }
  14526. this._activeChannel = channel;
  14527. if (internalTexture && internalTexture.is3D) {
  14528. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14529. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14530. internalTexture._cachedWrapU = texture.wrapU;
  14531. switch (texture.wrapU) {
  14532. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14533. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14534. break;
  14535. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14537. break;
  14538. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14540. break;
  14541. }
  14542. }
  14543. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14544. internalTexture._cachedWrapV = texture.wrapV;
  14545. switch (texture.wrapV) {
  14546. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14547. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14548. break;
  14549. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14550. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14551. break;
  14552. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14553. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14554. break;
  14555. }
  14556. }
  14557. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14558. internalTexture._cachedWrapR = texture.wrapR;
  14559. switch (texture.wrapR) {
  14560. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14561. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14562. break;
  14563. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14564. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14565. break;
  14566. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14567. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14568. break;
  14569. }
  14570. }
  14571. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14572. }
  14573. else if (internalTexture && internalTexture.isCube) {
  14574. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14575. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14576. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14577. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14578. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14579. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14580. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14581. }
  14582. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14583. }
  14584. else {
  14585. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14586. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14587. internalTexture._cachedWrapU = texture.wrapU;
  14588. switch (texture.wrapU) {
  14589. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14590. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14591. break;
  14592. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14593. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14594. break;
  14595. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14597. break;
  14598. }
  14599. }
  14600. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14601. internalTexture._cachedWrapV = texture.wrapV;
  14602. switch (texture.wrapV) {
  14603. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14604. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14605. break;
  14606. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14608. break;
  14609. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14611. break;
  14612. }
  14613. }
  14614. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14615. }
  14616. return true;
  14617. };
  14618. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14619. if (channel < 0 || !uniform) {
  14620. return;
  14621. }
  14622. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14623. this._textureUnits = new Int32Array(textures.length);
  14624. }
  14625. for (var i = 0; i < textures.length; i++) {
  14626. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14627. }
  14628. this._gl.uniform1iv(uniform, this._textureUnits);
  14629. for (var index = 0; index < textures.length; index++) {
  14630. this._setTexture(this._textureUnits[index], textures[index], true);
  14631. }
  14632. };
  14633. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14634. var internalTexture = texture.getInternalTexture();
  14635. if (!internalTexture) {
  14636. return;
  14637. }
  14638. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14639. var value = texture.anisotropicFilteringLevel;
  14640. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14641. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14642. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14643. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14644. }
  14645. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14646. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14647. internalTexture._cachedAnisotropicFilteringLevel = value;
  14648. }
  14649. };
  14650. Engine.prototype.readPixels = function (x, y, width, height) {
  14651. var data = new Uint8Array(height * width * 4);
  14652. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14653. return data;
  14654. };
  14655. /**
  14656. * Add an externaly attached data from its key.
  14657. * This method call will fail and return false, if such key already exists.
  14658. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14659. * @param key the unique key that identifies the data
  14660. * @param data the data object to associate to the key for this Engine instance
  14661. * @return true if no such key were already present and the data was added successfully, false otherwise
  14662. */
  14663. Engine.prototype.addExternalData = function (key, data) {
  14664. if (!this._externalData) {
  14665. this._externalData = new BABYLON.StringDictionary();
  14666. }
  14667. return this._externalData.add(key, data);
  14668. };
  14669. /**
  14670. * Get an externaly attached data from its key
  14671. * @param key the unique key that identifies the data
  14672. * @return the associated data, if present (can be null), or undefined if not present
  14673. */
  14674. Engine.prototype.getExternalData = function (key) {
  14675. if (!this._externalData) {
  14676. this._externalData = new BABYLON.StringDictionary();
  14677. }
  14678. return this._externalData.get(key);
  14679. };
  14680. /**
  14681. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14682. * @param key the unique key that identifies the data
  14683. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14684. * @return the associated data, can be null if the factory returned null.
  14685. */
  14686. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14687. if (!this._externalData) {
  14688. this._externalData = new BABYLON.StringDictionary();
  14689. }
  14690. return this._externalData.getOrAddWithFactory(key, factory);
  14691. };
  14692. /**
  14693. * Remove an externaly attached data from the Engine instance
  14694. * @param key the unique key that identifies the data
  14695. * @return true if the data was successfully removed, false if it doesn't exist
  14696. */
  14697. Engine.prototype.removeExternalData = function (key) {
  14698. if (!this._externalData) {
  14699. this._externalData = new BABYLON.StringDictionary();
  14700. }
  14701. return this._externalData.remove(key);
  14702. };
  14703. Engine.prototype.unbindAllAttributes = function () {
  14704. if (this._mustWipeVertexAttributes) {
  14705. this._mustWipeVertexAttributes = false;
  14706. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14707. this._gl.disableVertexAttribArray(i);
  14708. this._vertexAttribArraysEnabled[i] = false;
  14709. this._currentBufferPointers[i].active = false;
  14710. }
  14711. return;
  14712. }
  14713. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14714. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14715. continue;
  14716. }
  14717. this._gl.disableVertexAttribArray(i);
  14718. this._vertexAttribArraysEnabled[i] = false;
  14719. this._currentBufferPointers[i].active = false;
  14720. }
  14721. };
  14722. Engine.prototype.releaseEffects = function () {
  14723. for (var name in this._compiledEffects) {
  14724. this._deleteProgram(this._compiledEffects[name]._program);
  14725. }
  14726. this._compiledEffects = {};
  14727. };
  14728. // Dispose
  14729. Engine.prototype.dispose = function () {
  14730. this.hideLoadingUI();
  14731. this.stopRenderLoop();
  14732. // Release postProcesses
  14733. while (this.postProcesses.length) {
  14734. this.postProcesses[0].dispose();
  14735. }
  14736. // Empty texture
  14737. if (this._emptyTexture) {
  14738. this._releaseTexture(this._emptyTexture);
  14739. this._emptyTexture = null;
  14740. }
  14741. if (this._emptyCubeTexture) {
  14742. this._releaseTexture(this._emptyCubeTexture);
  14743. this._emptyCubeTexture = null;
  14744. }
  14745. // Rescale PP
  14746. if (this._rescalePostProcess) {
  14747. this._rescalePostProcess.dispose();
  14748. }
  14749. // Release scenes
  14750. while (this.scenes.length) {
  14751. this.scenes[0].dispose();
  14752. }
  14753. // Release audio engine
  14754. if (Engine.audioEngine) {
  14755. Engine.audioEngine.dispose();
  14756. }
  14757. // Release effects
  14758. this.releaseEffects();
  14759. // Unbind
  14760. this.unbindAllAttributes();
  14761. if (this._dummyFramebuffer) {
  14762. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14763. }
  14764. //WebVR
  14765. this.disableVR();
  14766. // Events
  14767. if (BABYLON.Tools.IsWindowObjectExist()) {
  14768. window.removeEventListener("blur", this._onBlur);
  14769. window.removeEventListener("focus", this._onFocus);
  14770. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14771. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14772. if (this._renderingCanvas) {
  14773. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14774. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14775. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14776. if (!this._doNotHandleContextLost) {
  14777. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14778. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14779. }
  14780. }
  14781. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14782. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14783. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14784. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14785. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14786. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14787. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14788. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14789. if (this._onVrDisplayConnect) {
  14790. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14791. if (this._onVrDisplayDisconnect) {
  14792. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14793. }
  14794. if (this._onVrDisplayPresentChange) {
  14795. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14796. }
  14797. this._onVrDisplayConnect = null;
  14798. this._onVrDisplayDisconnect = null;
  14799. }
  14800. }
  14801. // Remove from Instances
  14802. var index = Engine.Instances.indexOf(this);
  14803. if (index >= 0) {
  14804. Engine.Instances.splice(index, 1);
  14805. }
  14806. this._workingCanvas = null;
  14807. this._workingContext = null;
  14808. this._currentBufferPointers = [];
  14809. this._renderingCanvas = null;
  14810. this._currentProgram = null;
  14811. this.onResizeObservable.clear();
  14812. this.onCanvasBlurObservable.clear();
  14813. this.onCanvasFocusObservable.clear();
  14814. this.onCanvasPointerOutObservable.clear();
  14815. this.onBeginFrameObservable.clear();
  14816. this.onEndFrameObservable.clear();
  14817. BABYLON.Effect.ResetCache();
  14818. // Abort active requests
  14819. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14820. var request = _a[_i];
  14821. request.abort();
  14822. }
  14823. };
  14824. // Loading screen
  14825. Engine.prototype.displayLoadingUI = function () {
  14826. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14827. return;
  14828. }
  14829. var loadingScreen = this.loadingScreen;
  14830. if (loadingScreen) {
  14831. loadingScreen.displayLoadingUI();
  14832. }
  14833. };
  14834. Engine.prototype.hideLoadingUI = function () {
  14835. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14836. return;
  14837. }
  14838. var loadingScreen = this.loadingScreen;
  14839. if (loadingScreen) {
  14840. loadingScreen.hideLoadingUI();
  14841. }
  14842. };
  14843. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14844. get: function () {
  14845. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14846. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14847. return this._loadingScreen;
  14848. },
  14849. set: function (loadingScreen) {
  14850. this._loadingScreen = loadingScreen;
  14851. },
  14852. enumerable: true,
  14853. configurable: true
  14854. });
  14855. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14856. set: function (text) {
  14857. this.loadingScreen.loadingUIText = text;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14863. set: function (color) {
  14864. this.loadingScreen.loadingUIBackgroundColor = color;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. Engine.prototype.attachContextLostEvent = function (callback) {
  14870. if (this._renderingCanvas) {
  14871. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14872. }
  14873. };
  14874. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14875. if (this._renderingCanvas) {
  14876. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14877. }
  14878. };
  14879. Engine.prototype.getVertexShaderSource = function (program) {
  14880. var shaders = this._gl.getAttachedShaders(program);
  14881. if (!shaders) {
  14882. return null;
  14883. }
  14884. return this._gl.getShaderSource(shaders[0]);
  14885. };
  14886. Engine.prototype.getFragmentShaderSource = function (program) {
  14887. var shaders = this._gl.getAttachedShaders(program);
  14888. if (!shaders) {
  14889. return null;
  14890. }
  14891. return this._gl.getShaderSource(shaders[1]);
  14892. };
  14893. Engine.prototype.getError = function () {
  14894. return this._gl.getError();
  14895. };
  14896. // FPS
  14897. Engine.prototype.getFps = function () {
  14898. return this._fps;
  14899. };
  14900. Engine.prototype.getDeltaTime = function () {
  14901. return this._deltaTime;
  14902. };
  14903. Engine.prototype._measureFps = function () {
  14904. this._performanceMonitor.sampleFrame();
  14905. this._fps = this._performanceMonitor.averageFPS;
  14906. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14907. };
  14908. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14909. if (faceIndex === void 0) { faceIndex = -1; }
  14910. var gl = this._gl;
  14911. if (!this._dummyFramebuffer) {
  14912. var dummy = gl.createFramebuffer();
  14913. if (!dummy) {
  14914. throw new Error("Unable to create dummy framebuffer");
  14915. }
  14916. this._dummyFramebuffer = dummy;
  14917. }
  14918. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14919. if (faceIndex > -1) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14924. }
  14925. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14926. var buffer;
  14927. switch (readType) {
  14928. case gl.UNSIGNED_BYTE:
  14929. buffer = new Uint8Array(4 * width * height);
  14930. readType = gl.UNSIGNED_BYTE;
  14931. break;
  14932. default:
  14933. buffer = new Float32Array(4 * width * height);
  14934. readType = gl.FLOAT;
  14935. break;
  14936. }
  14937. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14938. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14939. return buffer;
  14940. };
  14941. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14942. if (this._webGLVersion > 1) {
  14943. return this._caps.colorBufferFloat;
  14944. }
  14945. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14946. };
  14947. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14948. if (this._webGLVersion > 1) {
  14949. return this._caps.colorBufferFloat;
  14950. }
  14951. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14952. };
  14953. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14954. Engine.prototype._canRenderToFramebuffer = function (type) {
  14955. var gl = this._gl;
  14956. //clear existing errors
  14957. while (gl.getError() !== gl.NO_ERROR) { }
  14958. var successful = true;
  14959. var texture = gl.createTexture();
  14960. gl.bindTexture(gl.TEXTURE_2D, texture);
  14961. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14964. var fb = gl.createFramebuffer();
  14965. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14967. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14968. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14969. successful = successful && (gl.getError() === gl.NO_ERROR);
  14970. //try render by clearing frame buffer's color buffer
  14971. if (successful) {
  14972. gl.clear(gl.COLOR_BUFFER_BIT);
  14973. successful = successful && (gl.getError() === gl.NO_ERROR);
  14974. }
  14975. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14976. if (successful) {
  14977. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14978. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14979. var readFormat = gl.RGBA;
  14980. var readType = gl.UNSIGNED_BYTE;
  14981. var buffer = new Uint8Array(4);
  14982. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14983. successful = successful && (gl.getError() === gl.NO_ERROR);
  14984. }
  14985. //clean up
  14986. gl.deleteTexture(texture);
  14987. gl.deleteFramebuffer(fb);
  14988. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14989. //clear accumulated errors
  14990. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14991. return successful;
  14992. };
  14993. Engine.prototype._getWebGLTextureType = function (type) {
  14994. if (type === Engine.TEXTURETYPE_FLOAT) {
  14995. return this._gl.FLOAT;
  14996. }
  14997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14998. // Add Half Float Constant.
  14999. return this._gl.HALF_FLOAT_OES;
  15000. }
  15001. return this._gl.UNSIGNED_BYTE;
  15002. };
  15003. ;
  15004. /** @ignore */
  15005. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15006. if (this._webGLVersion === 1) {
  15007. return this._gl.RGBA;
  15008. }
  15009. if (type === Engine.TEXTURETYPE_FLOAT) {
  15010. if (format) {
  15011. switch (format) {
  15012. case Engine.TEXTUREFORMAT_R32F:
  15013. return this._gl.R32F;
  15014. case Engine.TEXTUREFORMAT_RG32F:
  15015. return this._gl.RG32F;
  15016. case Engine.TEXTUREFORMAT_RGB32F:
  15017. return this._gl.RGB32F;
  15018. }
  15019. }
  15020. return this._gl.RGBA32F;
  15021. }
  15022. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15023. return this._gl.RGBA16F;
  15024. }
  15025. return this._gl.RGBA;
  15026. };
  15027. ;
  15028. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15029. if (type === Engine.TEXTURETYPE_FLOAT) {
  15030. return this._gl.RGBA32F;
  15031. }
  15032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15033. return this._gl.RGBA16F;
  15034. }
  15035. return this._gl.RGBA8;
  15036. };
  15037. ;
  15038. Engine.prototype.createQuery = function () {
  15039. return this._gl.createQuery();
  15040. };
  15041. Engine.prototype.deleteQuery = function (query) {
  15042. this._gl.deleteQuery(query);
  15043. return this;
  15044. };
  15045. Engine.prototype.isQueryResultAvailable = function (query) {
  15046. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15047. };
  15048. Engine.prototype.getQueryResult = function (query) {
  15049. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15050. };
  15051. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15052. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15053. this._gl.beginQuery(glAlgorithm, query);
  15054. return this;
  15055. };
  15056. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15057. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15058. this._gl.endQuery(glAlgorithm);
  15059. return this;
  15060. };
  15061. /* Time queries */
  15062. Engine.prototype._createTimeQuery = function () {
  15063. var timerQuery = this._caps.timerQuery;
  15064. if (timerQuery.createQueryEXT) {
  15065. return timerQuery.createQueryEXT();
  15066. }
  15067. return this.createQuery();
  15068. };
  15069. Engine.prototype._deleteTimeQuery = function (query) {
  15070. var timerQuery = this._caps.timerQuery;
  15071. if (timerQuery.deleteQueryEXT) {
  15072. timerQuery.deleteQueryEXT(query);
  15073. return;
  15074. }
  15075. this.deleteQuery(query);
  15076. };
  15077. Engine.prototype._getTimeQueryResult = function (query) {
  15078. var timerQuery = this._caps.timerQuery;
  15079. if (timerQuery.getQueryObjectEXT) {
  15080. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15081. }
  15082. return this.getQueryResult(query);
  15083. };
  15084. Engine.prototype._getTimeQueryAvailability = function (query) {
  15085. var timerQuery = this._caps.timerQuery;
  15086. if (timerQuery.getQueryObjectEXT) {
  15087. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15088. }
  15089. return this.isQueryResultAvailable(query);
  15090. };
  15091. Engine.prototype.startTimeQuery = function () {
  15092. var timerQuery = this._caps.timerQuery;
  15093. if (!timerQuery) {
  15094. return null;
  15095. }
  15096. var token = new BABYLON._TimeToken();
  15097. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15098. if (this._caps.canUseTimestampForTimerQuery) {
  15099. token._startTimeQuery = this._createTimeQuery();
  15100. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15101. }
  15102. else {
  15103. if (this._currentNonTimestampToken) {
  15104. return this._currentNonTimestampToken;
  15105. }
  15106. token._timeElapsedQuery = this._createTimeQuery();
  15107. if (timerQuery.beginQueryEXT) {
  15108. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15109. }
  15110. else {
  15111. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15112. }
  15113. this._currentNonTimestampToken = token;
  15114. }
  15115. return token;
  15116. };
  15117. Engine.prototype.endTimeQuery = function (token) {
  15118. var timerQuery = this._caps.timerQuery;
  15119. if (!timerQuery || !token) {
  15120. return -1;
  15121. }
  15122. if (this._caps.canUseTimestampForTimerQuery) {
  15123. if (!token._startTimeQuery) {
  15124. return -1;
  15125. }
  15126. if (!token._endTimeQuery) {
  15127. token._endTimeQuery = this._createTimeQuery();
  15128. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15129. }
  15130. }
  15131. else if (!token._timeElapsedQueryEnded) {
  15132. if (!token._timeElapsedQuery) {
  15133. return -1;
  15134. }
  15135. if (timerQuery.endQueryEXT) {
  15136. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15137. }
  15138. else {
  15139. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15140. }
  15141. token._timeElapsedQueryEnded = true;
  15142. }
  15143. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15144. var available = false;
  15145. if (token._endTimeQuery) {
  15146. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15147. }
  15148. else if (token._timeElapsedQuery) {
  15149. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15150. }
  15151. if (available && !disjoint) {
  15152. var result = 0;
  15153. if (this._caps.canUseTimestampForTimerQuery) {
  15154. if (!token._startTimeQuery || !token._endTimeQuery) {
  15155. return -1;
  15156. }
  15157. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15158. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15159. result = timeEnd - timeStart;
  15160. this._deleteTimeQuery(token._startTimeQuery);
  15161. this._deleteTimeQuery(token._endTimeQuery);
  15162. token._startTimeQuery = null;
  15163. token._endTimeQuery = null;
  15164. }
  15165. else {
  15166. if (!token._timeElapsedQuery) {
  15167. return -1;
  15168. }
  15169. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15170. this._deleteTimeQuery(token._timeElapsedQuery);
  15171. token._timeElapsedQuery = null;
  15172. token._timeElapsedQueryEnded = false;
  15173. this._currentNonTimestampToken = null;
  15174. }
  15175. return result;
  15176. }
  15177. return -1;
  15178. };
  15179. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15180. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15181. };
  15182. // Transform feedback
  15183. Engine.prototype.createTransformFeedback = function () {
  15184. return this._gl.createTransformFeedback();
  15185. };
  15186. Engine.prototype.deleteTransformFeedback = function (value) {
  15187. this._gl.deleteTransformFeedback(value);
  15188. };
  15189. Engine.prototype.bindTransformFeedback = function (value) {
  15190. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15191. };
  15192. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15193. if (usePoints === void 0) { usePoints = true; }
  15194. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15195. };
  15196. Engine.prototype.endTransformFeedback = function () {
  15197. this._gl.endTransformFeedback();
  15198. };
  15199. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15200. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15201. };
  15202. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15203. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15204. };
  15205. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15206. var _this = this;
  15207. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15208. this._activeRequests.push(request);
  15209. request.onCompleteObservable.add(function (request) {
  15210. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15211. });
  15212. return request;
  15213. };
  15214. /** @ignore */
  15215. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15216. var _this = this;
  15217. return new Promise(function (resolve, reject) {
  15218. _this._loadFile(url, function (data) {
  15219. resolve(data);
  15220. }, undefined, database, useArrayBuffer, function (request, exception) {
  15221. reject(exception);
  15222. });
  15223. });
  15224. };
  15225. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15226. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15227. var onload = function (data) {
  15228. loadedFiles[index] = data;
  15229. loadedFiles._internalCount++;
  15230. if (loadedFiles._internalCount === 6) {
  15231. onfinish(loadedFiles);
  15232. }
  15233. };
  15234. var onerror = function (request, exception) {
  15235. if (onErrorCallBack && request) {
  15236. onErrorCallBack(request.status + " " + request.statusText, exception);
  15237. }
  15238. };
  15239. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15240. };
  15241. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15242. if (onError === void 0) { onError = null; }
  15243. var loadedFiles = [];
  15244. loadedFiles._internalCount = 0;
  15245. for (var index = 0; index < 6; index++) {
  15246. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15247. }
  15248. };
  15249. // Statics
  15250. Engine.isSupported = function () {
  15251. try {
  15252. var tempcanvas = document.createElement("canvas");
  15253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15254. return gl != null && !!window.WebGLRenderingContext;
  15255. }
  15256. catch (e) {
  15257. return false;
  15258. }
  15259. };
  15260. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15261. Engine.ExceptionList = [
  15262. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15263. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15264. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15265. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15266. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15267. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15268. ];
  15269. Engine.Instances = new Array();
  15270. // Const statics
  15271. Engine._ALPHA_DISABLE = 0;
  15272. Engine._ALPHA_ADD = 1;
  15273. Engine._ALPHA_COMBINE = 2;
  15274. Engine._ALPHA_SUBTRACT = 3;
  15275. Engine._ALPHA_MULTIPLY = 4;
  15276. Engine._ALPHA_MAXIMIZED = 5;
  15277. Engine._ALPHA_ONEONE = 6;
  15278. Engine._ALPHA_PREMULTIPLIED = 7;
  15279. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15280. Engine._ALPHA_INTERPOLATE = 9;
  15281. Engine._ALPHA_SCREENMODE = 10;
  15282. Engine._DELAYLOADSTATE_NONE = 0;
  15283. Engine._DELAYLOADSTATE_LOADED = 1;
  15284. Engine._DELAYLOADSTATE_LOADING = 2;
  15285. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15286. Engine._TEXTUREFORMAT_ALPHA = 0;
  15287. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15288. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15289. Engine._TEXTUREFORMAT_RGB = 4;
  15290. Engine._TEXTUREFORMAT_RGBA = 5;
  15291. Engine._TEXTUREFORMAT_R32F = 6;
  15292. Engine._TEXTUREFORMAT_RG32F = 7;
  15293. Engine._TEXTUREFORMAT_RGB32F = 8;
  15294. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15295. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15296. Engine._TEXTURETYPE_FLOAT = 1;
  15297. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15298. // Depht or Stencil test Constants.
  15299. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15300. 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.
  15301. 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.
  15302. 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.
  15303. 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.
  15304. 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.
  15305. 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.
  15306. 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.
  15307. // Stencil Actions Constants.
  15308. Engine._KEEP = 0x1E00;
  15309. Engine._REPLACE = 0x1E01;
  15310. Engine._INCR = 0x1E02;
  15311. Engine._DECR = 0x1E03;
  15312. Engine._INVERT = 0x150A;
  15313. Engine._INCR_WRAP = 0x8507;
  15314. Engine._DECR_WRAP = 0x8508;
  15315. // Texture rescaling mode
  15316. Engine._SCALEMODE_FLOOR = 1;
  15317. Engine._SCALEMODE_NEAREST = 2;
  15318. Engine._SCALEMODE_CEILING = 3;
  15319. // Updatable statics so stick with vars here
  15320. Engine.CollisionsEpsilon = 0.001;
  15321. Engine.CodeRepository = "src/";
  15322. Engine.ShadersRepository = "src/Shaders/";
  15323. return Engine;
  15324. }());
  15325. BABYLON.Engine = Engine;
  15326. })(BABYLON || (BABYLON = {}));
  15327. //# sourceMappingURL=babylon.engine.js.map
  15328. var BABYLON;
  15329. (function (BABYLON) {
  15330. /**
  15331. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15332. */
  15333. var Node = /** @class */ (function () {
  15334. /**
  15335. * Creates a new Node
  15336. * @param {string} name - the name and id to be given to this node
  15337. * @param {BABYLON.Scene} the scene this node will be added to
  15338. */
  15339. function Node(name, scene) {
  15340. if (scene === void 0) { scene = null; }
  15341. /**
  15342. * Gets or sets a string used to store user defined state for the node
  15343. */
  15344. this.state = "";
  15345. /**
  15346. * Gets or sets an object used to store user defined information for the node
  15347. */
  15348. this.metadata = null;
  15349. /**
  15350. * Gets or sets a boolean used to define if the node must be serialized
  15351. */
  15352. this.doNotSerialize = false;
  15353. /** @ignore */
  15354. this._isDisposed = false;
  15355. /**
  15356. * Gets a list of {BABYLON.Animation} associated with the node
  15357. */
  15358. this.animations = new Array();
  15359. this._ranges = {};
  15360. this._isEnabled = true;
  15361. this._isReady = true;
  15362. /** @ignore */
  15363. this._currentRenderId = -1;
  15364. this._parentRenderId = -1;
  15365. this._animationPropertiesOverride = null;
  15366. /**
  15367. * An event triggered when the mesh is disposed
  15368. * @type {BABYLON.Observable}
  15369. */
  15370. this.onDisposeObservable = new BABYLON.Observable();
  15371. // Behaviors
  15372. this._behaviors = new Array();
  15373. this.name = name;
  15374. this.id = name;
  15375. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15376. this.uniqueId = this._scene.getUniqueId();
  15377. this._initCache();
  15378. }
  15379. /**
  15380. * Gets a boolean indicating if the node has been disposed
  15381. * @returns true if the node was disposed
  15382. */
  15383. Node.prototype.isDisposed = function () {
  15384. return this._isDisposed;
  15385. };
  15386. Object.defineProperty(Node.prototype, "parent", {
  15387. get: function () {
  15388. return this._parentNode;
  15389. },
  15390. /**
  15391. * Gets or sets the parent of the node
  15392. */
  15393. set: function (parent) {
  15394. if (this._parentNode === parent) {
  15395. return;
  15396. }
  15397. // Remove self from list of children of parent
  15398. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15399. var index = this._parentNode._children.indexOf(this);
  15400. if (index !== -1) {
  15401. this._parentNode._children.splice(index, 1);
  15402. }
  15403. }
  15404. // Store new parent
  15405. this._parentNode = parent;
  15406. // Add as child to new parent
  15407. if (this._parentNode) {
  15408. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15409. this._parentNode._children = new Array();
  15410. }
  15411. this._parentNode._children.push(this);
  15412. }
  15413. },
  15414. enumerable: true,
  15415. configurable: true
  15416. });
  15417. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15418. /**
  15419. * Gets or sets the animation properties override
  15420. */
  15421. get: function () {
  15422. return this._animationPropertiesOverride;
  15423. },
  15424. set: function (value) {
  15425. this._animationPropertiesOverride = value;
  15426. },
  15427. enumerable: true,
  15428. configurable: true
  15429. });
  15430. /**
  15431. * Gets a string idenfifying the name of the class
  15432. * @returns "Node" string
  15433. */
  15434. Node.prototype.getClassName = function () {
  15435. return "Node";
  15436. };
  15437. Object.defineProperty(Node.prototype, "onDispose", {
  15438. /**
  15439. * Sets a callback that will be raised when the node will be disposed
  15440. */
  15441. set: function (callback) {
  15442. if (this._onDisposeObserver) {
  15443. this.onDisposeObservable.remove(this._onDisposeObserver);
  15444. }
  15445. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15446. },
  15447. enumerable: true,
  15448. configurable: true
  15449. });
  15450. /**
  15451. * Gets the scene of the node
  15452. * @returns a {BABYLON.Scene}
  15453. */
  15454. Node.prototype.getScene = function () {
  15455. return this._scene;
  15456. };
  15457. /**
  15458. * Gets the engine of the node
  15459. * @returns a {BABYLON.Engine}
  15460. */
  15461. Node.prototype.getEngine = function () {
  15462. return this._scene.getEngine();
  15463. };
  15464. /**
  15465. * Attach a behavior to the node
  15466. * @see http://doc.babylonjs.com/features/behaviour
  15467. * @param behavior defines the behavior to attach
  15468. * @returns the current Node
  15469. */
  15470. Node.prototype.addBehavior = function (behavior) {
  15471. var _this = this;
  15472. var index = this._behaviors.indexOf(behavior);
  15473. if (index !== -1) {
  15474. return this;
  15475. }
  15476. behavior.init();
  15477. if (this._scene.isLoading) {
  15478. // We defer the attach when the scene will be loaded
  15479. var observer = this._scene.onDataLoadedObservable.add(function () {
  15480. behavior.attach(_this);
  15481. setTimeout(function () {
  15482. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15483. _this._scene.onDataLoadedObservable.remove(observer);
  15484. }, 0);
  15485. });
  15486. }
  15487. else {
  15488. behavior.attach(this);
  15489. }
  15490. this._behaviors.push(behavior);
  15491. return this;
  15492. };
  15493. /**
  15494. * Remove an attached behavior
  15495. * @see http://doc.babylonjs.com/features/behaviour
  15496. * @param behavior defines the behavior to attach
  15497. * @returns the current Node
  15498. */
  15499. Node.prototype.removeBehavior = function (behavior) {
  15500. var index = this._behaviors.indexOf(behavior);
  15501. if (index === -1) {
  15502. return this;
  15503. }
  15504. this._behaviors[index].detach();
  15505. this._behaviors.splice(index, 1);
  15506. return this;
  15507. };
  15508. Object.defineProperty(Node.prototype, "behaviors", {
  15509. /**
  15510. * Gets the list of attached behaviors
  15511. * @see http://doc.babylonjs.com/features/behaviour
  15512. */
  15513. get: function () {
  15514. return this._behaviors;
  15515. },
  15516. enumerable: true,
  15517. configurable: true
  15518. });
  15519. /**
  15520. * Gets an attached behavior by name
  15521. * @param name defines the name of the behavior to look for
  15522. * @see http://doc.babylonjs.com/features/behaviour
  15523. * @returns null if behavior was not found else the requested behavior
  15524. */
  15525. Node.prototype.getBehaviorByName = function (name) {
  15526. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15527. var behavior = _a[_i];
  15528. if (behavior.name === name) {
  15529. return behavior;
  15530. }
  15531. }
  15532. return null;
  15533. };
  15534. /**
  15535. * Returns the world matrix of the node
  15536. * @returns a matrix containing the node's world matrix
  15537. */
  15538. Node.prototype.getWorldMatrix = function () {
  15539. return BABYLON.Matrix.Identity();
  15540. };
  15541. // override it in derived class if you add new variables to the cache
  15542. // and call the parent class method
  15543. /** @ignore */
  15544. Node.prototype._initCache = function () {
  15545. this._cache = {};
  15546. this._cache.parent = undefined;
  15547. };
  15548. /** @ignore */
  15549. Node.prototype.updateCache = function (force) {
  15550. if (!force && this.isSynchronized())
  15551. return;
  15552. this._cache.parent = this.parent;
  15553. this._updateCache();
  15554. };
  15555. // override it in derived class if you add new variables to the cache
  15556. // and call the parent class method if !ignoreParentClass
  15557. /** @ignore */
  15558. Node.prototype._updateCache = function (ignoreParentClass) {
  15559. };
  15560. // override it in derived class if you add new variables to the cache
  15561. /** @ignore */
  15562. Node.prototype._isSynchronized = function () {
  15563. return true;
  15564. };
  15565. /** @ignore */
  15566. Node.prototype._markSyncedWithParent = function () {
  15567. if (this.parent) {
  15568. this._parentRenderId = this.parent._currentRenderId;
  15569. }
  15570. };
  15571. /** @ignore */
  15572. Node.prototype.isSynchronizedWithParent = function () {
  15573. if (!this.parent) {
  15574. return true;
  15575. }
  15576. if (this._parentRenderId !== this.parent._currentRenderId) {
  15577. return false;
  15578. }
  15579. return this.parent.isSynchronized();
  15580. };
  15581. /** @ignore */
  15582. Node.prototype.isSynchronized = function (updateCache) {
  15583. var check = this.hasNewParent();
  15584. check = check || !this.isSynchronizedWithParent();
  15585. check = check || !this._isSynchronized();
  15586. if (updateCache)
  15587. this.updateCache(true);
  15588. return !check;
  15589. };
  15590. /** @ignore */
  15591. Node.prototype.hasNewParent = function (update) {
  15592. if (this._cache.parent === this.parent)
  15593. return false;
  15594. if (update)
  15595. this._cache.parent = this.parent;
  15596. return true;
  15597. };
  15598. /**
  15599. * Is this node ready to be used/rendered
  15600. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15601. * @return true if the node is ready
  15602. */
  15603. Node.prototype.isReady = function (completeCheck) {
  15604. if (completeCheck === void 0) { completeCheck = false; }
  15605. return this._isReady;
  15606. };
  15607. /**
  15608. * Is this node enabled?
  15609. * 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
  15610. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15611. * @return whether this node (and its parent) is enabled
  15612. * @see setEnabled
  15613. */
  15614. Node.prototype.isEnabled = function (checkAncestors) {
  15615. if (checkAncestors === void 0) { checkAncestors = true; }
  15616. if (checkAncestors === false) {
  15617. return this._isEnabled;
  15618. }
  15619. if (this._isEnabled === false) {
  15620. return false;
  15621. }
  15622. if (this.parent !== undefined && this.parent !== null) {
  15623. return this.parent.isEnabled(checkAncestors);
  15624. }
  15625. return true;
  15626. };
  15627. /**
  15628. * Set the enabled state of this node
  15629. * @param value defines the new enabled state
  15630. * @see isEnabled
  15631. */
  15632. Node.prototype.setEnabled = function (value) {
  15633. this._isEnabled = value;
  15634. };
  15635. /**
  15636. * Is this node a descendant of the given node?
  15637. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15638. * @param ancestor defines the parent node to inspect
  15639. * @see parent
  15640. * @returns a boolean indicating if this node is a descendant of the given node
  15641. */
  15642. Node.prototype.isDescendantOf = function (ancestor) {
  15643. if (this.parent) {
  15644. if (this.parent === ancestor) {
  15645. return true;
  15646. }
  15647. return this.parent.isDescendantOf(ancestor);
  15648. }
  15649. return false;
  15650. };
  15651. /** @ignore */
  15652. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15653. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15654. if (!this._children) {
  15655. return;
  15656. }
  15657. for (var index = 0; index < this._children.length; index++) {
  15658. var item = this._children[index];
  15659. if (!predicate || predicate(item)) {
  15660. results.push(item);
  15661. }
  15662. if (!directDescendantsOnly) {
  15663. item._getDescendants(results, false, predicate);
  15664. }
  15665. }
  15666. };
  15667. /**
  15668. * Will return all nodes that have this node as ascendant
  15669. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15670. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15671. * @return all children nodes of all types
  15672. */
  15673. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15674. var results = new Array();
  15675. this._getDescendants(results, directDescendantsOnly, predicate);
  15676. return results;
  15677. };
  15678. /**
  15679. * Get all child-meshes of this node
  15680. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15681. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15682. * @returns an array of {BABYLON.AbstractMesh}
  15683. */
  15684. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15685. var results = [];
  15686. this._getDescendants(results, directDescendantsOnly, function (node) {
  15687. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15688. });
  15689. return results;
  15690. };
  15691. /**
  15692. * Get all child-transformNodes of this node
  15693. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15694. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15695. * @returns an array of {BABYLON.TransformNode}
  15696. */
  15697. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15698. var results = [];
  15699. this._getDescendants(results, directDescendantsOnly, function (node) {
  15700. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15701. });
  15702. return results;
  15703. };
  15704. /**
  15705. * Get all direct children of this node
  15706. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15707. * @returns an array of {BABYLON.Node}
  15708. */
  15709. Node.prototype.getChildren = function (predicate) {
  15710. return this.getDescendants(true, predicate);
  15711. };
  15712. /** @ignore */
  15713. Node.prototype._setReady = function (state) {
  15714. if (state === this._isReady) {
  15715. return;
  15716. }
  15717. if (!state) {
  15718. this._isReady = false;
  15719. return;
  15720. }
  15721. this._isReady = true;
  15722. if (this.onReady) {
  15723. this.onReady(this);
  15724. }
  15725. };
  15726. /**
  15727. * Get an animation by name
  15728. * @param name defines the name of the animation to look for
  15729. * @returns null if not found else the requested animation
  15730. */
  15731. Node.prototype.getAnimationByName = function (name) {
  15732. for (var i = 0; i < this.animations.length; i++) {
  15733. var animation = this.animations[i];
  15734. if (animation.name === name) {
  15735. return animation;
  15736. }
  15737. }
  15738. return null;
  15739. };
  15740. /**
  15741. * Creates an animation range for this node
  15742. * @param name defines the name of the range
  15743. * @param from defines the starting key
  15744. * @param to defines the end key
  15745. */
  15746. Node.prototype.createAnimationRange = function (name, from, to) {
  15747. // check name not already in use
  15748. if (!this._ranges[name]) {
  15749. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15750. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15751. if (this.animations[i]) {
  15752. this.animations[i].createRange(name, from, to);
  15753. }
  15754. }
  15755. }
  15756. };
  15757. /**
  15758. * Delete a specific animation range
  15759. * @param name defines the name of the range to delete
  15760. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15761. */
  15762. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15763. if (deleteFrames === void 0) { deleteFrames = true; }
  15764. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15765. if (this.animations[i]) {
  15766. this.animations[i].deleteRange(name, deleteFrames);
  15767. }
  15768. }
  15769. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15770. };
  15771. /**
  15772. * Get an animation range by name
  15773. * @param name defines the name of the animation range to look for
  15774. * @returns null if not found else the requested animation range
  15775. */
  15776. Node.prototype.getAnimationRange = function (name) {
  15777. return this._ranges[name];
  15778. };
  15779. /**
  15780. * Will start the animation sequence
  15781. * @param name defines the range frames for animation sequence
  15782. * @param loop defines if the animation should loop (false by default)
  15783. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15784. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15785. * @returns the object created for this animation. If range does not exist, it will return null
  15786. */
  15787. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15788. var range = this.getAnimationRange(name);
  15789. if (!range) {
  15790. return null;
  15791. }
  15792. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15793. };
  15794. /**
  15795. * Serialize animation ranges into a JSON compatible object
  15796. * @returns serialization object
  15797. */
  15798. Node.prototype.serializeAnimationRanges = function () {
  15799. var serializationRanges = [];
  15800. for (var name in this._ranges) {
  15801. var localRange = this._ranges[name];
  15802. if (!localRange) {
  15803. continue;
  15804. }
  15805. var range = {};
  15806. range.name = name;
  15807. range.from = localRange.from;
  15808. range.to = localRange.to;
  15809. serializationRanges.push(range);
  15810. }
  15811. return serializationRanges;
  15812. };
  15813. /**
  15814. * Computes the world matrix of the node
  15815. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15816. * @returns the world matrix
  15817. */
  15818. Node.prototype.computeWorldMatrix = function (force) {
  15819. return BABYLON.Matrix.Identity();
  15820. };
  15821. /**
  15822. * Releases all associated resources
  15823. */
  15824. Node.prototype.dispose = function () {
  15825. this.parent = null;
  15826. // Callback
  15827. this.onDisposeObservable.notifyObservers(this);
  15828. this.onDisposeObservable.clear();
  15829. // Behaviors
  15830. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15831. var behavior = _a[_i];
  15832. behavior.detach();
  15833. }
  15834. this._behaviors = [];
  15835. this._isDisposed = true;
  15836. };
  15837. /**
  15838. * Parse animation range data from a serialization object and store them into a given node
  15839. * @param node defines where to store the animation ranges
  15840. * @param parsedNode defines the serialization object to read data from
  15841. * @param scene defines the hosting scene
  15842. */
  15843. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15844. if (parsedNode.ranges) {
  15845. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15846. var data = parsedNode.ranges[index];
  15847. node.createAnimationRange(data.name, data.from, data.to);
  15848. }
  15849. }
  15850. };
  15851. __decorate([
  15852. BABYLON.serialize()
  15853. ], Node.prototype, "name", void 0);
  15854. __decorate([
  15855. BABYLON.serialize()
  15856. ], Node.prototype, "id", void 0);
  15857. __decorate([
  15858. BABYLON.serialize()
  15859. ], Node.prototype, "uniqueId", void 0);
  15860. __decorate([
  15861. BABYLON.serialize()
  15862. ], Node.prototype, "state", void 0);
  15863. __decorate([
  15864. BABYLON.serialize()
  15865. ], Node.prototype, "metadata", void 0);
  15866. return Node;
  15867. }());
  15868. BABYLON.Node = Node;
  15869. })(BABYLON || (BABYLON = {}));
  15870. //# sourceMappingURL=babylon.node.js.map
  15871. var BABYLON;
  15872. (function (BABYLON) {
  15873. var BoundingSphere = /** @class */ (function () {
  15874. function BoundingSphere(minimum, maximum) {
  15875. this.minimum = minimum;
  15876. this.maximum = maximum;
  15877. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15878. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15879. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15880. this.radius = distance * 0.5;
  15881. this.centerWorld = BABYLON.Vector3.Zero();
  15882. this._update(BABYLON.Matrix.Identity());
  15883. }
  15884. // Methods
  15885. BoundingSphere.prototype._update = function (world) {
  15886. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15887. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15888. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15889. };
  15890. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15891. for (var i = 0; i < 6; i++) {
  15892. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15893. return false;
  15894. }
  15895. return true;
  15896. };
  15897. BoundingSphere.prototype.intersectsPoint = function (point) {
  15898. var x = this.centerWorld.x - point.x;
  15899. var y = this.centerWorld.y - point.y;
  15900. var z = this.centerWorld.z - point.z;
  15901. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15902. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15903. return false;
  15904. return true;
  15905. };
  15906. // Statics
  15907. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15908. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15909. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15910. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15911. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15912. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15913. return false;
  15914. return true;
  15915. };
  15916. return BoundingSphere;
  15917. }());
  15918. BABYLON.BoundingSphere = BoundingSphere;
  15919. })(BABYLON || (BABYLON = {}));
  15920. //# sourceMappingURL=babylon.boundingSphere.js.map
  15921. var BABYLON;
  15922. (function (BABYLON) {
  15923. var BoundingBox = /** @class */ (function () {
  15924. function BoundingBox(minimum, maximum) {
  15925. this.minimum = minimum;
  15926. this.maximum = maximum;
  15927. this.vectors = new Array();
  15928. this.vectorsWorld = new Array();
  15929. // Bounding vectors
  15930. this.vectors.push(this.minimum.clone());
  15931. this.vectors.push(this.maximum.clone());
  15932. this.vectors.push(this.minimum.clone());
  15933. this.vectors[2].x = this.maximum.x;
  15934. this.vectors.push(this.minimum.clone());
  15935. this.vectors[3].y = this.maximum.y;
  15936. this.vectors.push(this.minimum.clone());
  15937. this.vectors[4].z = this.maximum.z;
  15938. this.vectors.push(this.maximum.clone());
  15939. this.vectors[5].z = this.minimum.z;
  15940. this.vectors.push(this.maximum.clone());
  15941. this.vectors[6].x = this.minimum.x;
  15942. this.vectors.push(this.maximum.clone());
  15943. this.vectors[7].y = this.minimum.y;
  15944. // OBB
  15945. this.center = this.maximum.add(this.minimum).scale(0.5);
  15946. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15947. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15948. // World
  15949. for (var index = 0; index < this.vectors.length; index++) {
  15950. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15951. }
  15952. this.minimumWorld = BABYLON.Vector3.Zero();
  15953. this.maximumWorld = BABYLON.Vector3.Zero();
  15954. this.centerWorld = BABYLON.Vector3.Zero();
  15955. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15956. this._update(BABYLON.Matrix.Identity());
  15957. }
  15958. // Methods
  15959. BoundingBox.prototype.getWorldMatrix = function () {
  15960. return this._worldMatrix;
  15961. };
  15962. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15963. this._worldMatrix.copyFrom(matrix);
  15964. return this;
  15965. };
  15966. BoundingBox.prototype._update = function (world) {
  15967. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15968. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15969. for (var index = 0; index < this.vectors.length; index++) {
  15970. var v = this.vectorsWorld[index];
  15971. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15972. if (v.x < this.minimumWorld.x)
  15973. this.minimumWorld.x = v.x;
  15974. if (v.y < this.minimumWorld.y)
  15975. this.minimumWorld.y = v.y;
  15976. if (v.z < this.minimumWorld.z)
  15977. this.minimumWorld.z = v.z;
  15978. if (v.x > this.maximumWorld.x)
  15979. this.maximumWorld.x = v.x;
  15980. if (v.y > this.maximumWorld.y)
  15981. this.maximumWorld.y = v.y;
  15982. if (v.z > this.maximumWorld.z)
  15983. this.maximumWorld.z = v.z;
  15984. }
  15985. // Extend
  15986. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15987. this.extendSizeWorld.scaleInPlace(0.5);
  15988. // OBB
  15989. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15990. this.centerWorld.scaleInPlace(0.5);
  15991. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15992. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15993. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15994. this._worldMatrix = world;
  15995. };
  15996. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15997. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15998. };
  15999. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16000. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16001. };
  16002. BoundingBox.prototype.intersectsPoint = function (point) {
  16003. var delta = -BABYLON.Epsilon;
  16004. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16005. return false;
  16006. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16007. return false;
  16008. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16009. return false;
  16010. return true;
  16011. };
  16012. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16013. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16014. };
  16015. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16016. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16017. return false;
  16018. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16019. return false;
  16020. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16021. return false;
  16022. return true;
  16023. };
  16024. // Statics
  16025. BoundingBox.Intersects = function (box0, box1) {
  16026. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16027. return false;
  16028. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16029. return false;
  16030. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16031. return false;
  16032. return true;
  16033. };
  16034. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16035. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16036. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16037. return (num <= (sphereRadius * sphereRadius));
  16038. };
  16039. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16040. for (var p = 0; p < 6; p++) {
  16041. for (var i = 0; i < 8; i++) {
  16042. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16043. return false;
  16044. }
  16045. }
  16046. }
  16047. return true;
  16048. };
  16049. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16050. for (var p = 0; p < 6; p++) {
  16051. var inCount = 8;
  16052. for (var i = 0; i < 8; i++) {
  16053. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16054. --inCount;
  16055. }
  16056. else {
  16057. break;
  16058. }
  16059. }
  16060. if (inCount === 0)
  16061. return false;
  16062. }
  16063. return true;
  16064. };
  16065. return BoundingBox;
  16066. }());
  16067. BABYLON.BoundingBox = BoundingBox;
  16068. })(BABYLON || (BABYLON = {}));
  16069. //# sourceMappingURL=babylon.boundingBox.js.map
  16070. var BABYLON;
  16071. (function (BABYLON) {
  16072. var computeBoxExtents = function (axis, box) {
  16073. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16074. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16075. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16076. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16077. var r = r0 + r1 + r2;
  16078. return {
  16079. min: p - r,
  16080. max: p + r
  16081. };
  16082. };
  16083. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16084. var axisOverlap = function (axis, box0, box1) {
  16085. var result0 = computeBoxExtents(axis, box0);
  16086. var result1 = computeBoxExtents(axis, box1);
  16087. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16088. };
  16089. var BoundingInfo = /** @class */ (function () {
  16090. function BoundingInfo(minimum, maximum) {
  16091. this.minimum = minimum;
  16092. this.maximum = maximum;
  16093. this._isLocked = false;
  16094. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16095. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16096. }
  16097. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16098. get: function () {
  16099. return this._isLocked;
  16100. },
  16101. set: function (value) {
  16102. this._isLocked = value;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. // Methods
  16108. BoundingInfo.prototype.update = function (world) {
  16109. if (this._isLocked) {
  16110. return;
  16111. }
  16112. this.boundingBox._update(world);
  16113. this.boundingSphere._update(world);
  16114. };
  16115. /**
  16116. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16117. * @param center New center of the bounding info
  16118. * @param extend New extend of the bounding info
  16119. */
  16120. BoundingInfo.prototype.centerOn = function (center, extend) {
  16121. this.minimum = center.subtract(extend);
  16122. this.maximum = center.add(extend);
  16123. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16124. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16125. return this;
  16126. };
  16127. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16128. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16129. return false;
  16130. return this.boundingBox.isInFrustum(frustumPlanes);
  16131. };
  16132. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16133. /**
  16134. * Gets the world distance between the min and max points of the bounding box
  16135. */
  16136. get: function () {
  16137. var boundingBox = this.boundingBox;
  16138. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16139. return size.length();
  16140. },
  16141. enumerable: true,
  16142. configurable: true
  16143. });
  16144. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16145. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16146. };
  16147. BoundingInfo.prototype._checkCollision = function (collider) {
  16148. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16149. };
  16150. BoundingInfo.prototype.intersectsPoint = function (point) {
  16151. if (!this.boundingSphere.centerWorld) {
  16152. return false;
  16153. }
  16154. if (!this.boundingSphere.intersectsPoint(point)) {
  16155. return false;
  16156. }
  16157. if (!this.boundingBox.intersectsPoint(point)) {
  16158. return false;
  16159. }
  16160. return true;
  16161. };
  16162. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16163. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16164. return false;
  16165. }
  16166. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16167. return false;
  16168. }
  16169. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16170. return false;
  16171. }
  16172. if (!precise) {
  16173. return true;
  16174. }
  16175. var box0 = this.boundingBox;
  16176. var box1 = boundingInfo.boundingBox;
  16177. if (!axisOverlap(box0.directions[0], box0, box1))
  16178. return false;
  16179. if (!axisOverlap(box0.directions[1], box0, box1))
  16180. return false;
  16181. if (!axisOverlap(box0.directions[2], box0, box1))
  16182. return false;
  16183. if (!axisOverlap(box1.directions[0], box0, box1))
  16184. return false;
  16185. if (!axisOverlap(box1.directions[1], box0, box1))
  16186. return false;
  16187. if (!axisOverlap(box1.directions[2], box0, box1))
  16188. return false;
  16189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16190. return false;
  16191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16192. return false;
  16193. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16194. return false;
  16195. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16196. return false;
  16197. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16198. return false;
  16199. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16200. return false;
  16201. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16202. return false;
  16203. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16204. return false;
  16205. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16206. return false;
  16207. return true;
  16208. };
  16209. return BoundingInfo;
  16210. }());
  16211. BABYLON.BoundingInfo = BoundingInfo;
  16212. })(BABYLON || (BABYLON = {}));
  16213. //# sourceMappingURL=babylon.boundingInfo.js.map
  16214. var BABYLON;
  16215. (function (BABYLON) {
  16216. var TransformNode = /** @class */ (function (_super) {
  16217. __extends(TransformNode, _super);
  16218. function TransformNode(name, scene, isPure) {
  16219. if (scene === void 0) { scene = null; }
  16220. if (isPure === void 0) { isPure = true; }
  16221. var _this = _super.call(this, name, scene) || this;
  16222. // Properties
  16223. _this._rotation = BABYLON.Vector3.Zero();
  16224. _this._scaling = BABYLON.Vector3.One();
  16225. _this._isDirty = false;
  16226. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16227. _this.scalingDeterminant = 1;
  16228. _this.infiniteDistance = false;
  16229. _this.position = BABYLON.Vector3.Zero();
  16230. _this._localWorld = BABYLON.Matrix.Zero();
  16231. _this._worldMatrix = BABYLON.Matrix.Zero();
  16232. _this._worldMatrixDeterminant = 0;
  16233. _this._absolutePosition = BABYLON.Vector3.Zero();
  16234. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16235. _this._postMultiplyPivotMatrix = false;
  16236. _this._isWorldMatrixFrozen = false;
  16237. /**
  16238. * An event triggered after the world matrix is updated
  16239. * @type {BABYLON.Observable}
  16240. */
  16241. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16242. _this._nonUniformScaling = false;
  16243. if (isPure) {
  16244. _this.getScene().addTransformNode(_this);
  16245. }
  16246. return _this;
  16247. }
  16248. Object.defineProperty(TransformNode.prototype, "rotation", {
  16249. /**
  16250. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16251. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16252. * Default : (0.0, 0.0, 0.0)
  16253. */
  16254. get: function () {
  16255. return this._rotation;
  16256. },
  16257. set: function (newRotation) {
  16258. this._rotation = newRotation;
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Object.defineProperty(TransformNode.prototype, "scaling", {
  16264. /**
  16265. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16266. * Default : (1.0, 1.0, 1.0)
  16267. */
  16268. get: function () {
  16269. return this._scaling;
  16270. },
  16271. /**
  16272. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16273. * Default : (1.0, 1.0, 1.0)
  16274. */
  16275. set: function (newScaling) {
  16276. this._scaling = newScaling;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16282. /**
  16283. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16284. * It's null by default.
  16285. * 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)
  16286. */
  16287. get: function () {
  16288. return this._rotationQuaternion;
  16289. },
  16290. set: function (quaternion) {
  16291. this._rotationQuaternion = quaternion;
  16292. //reset the rotation vector.
  16293. if (quaternion && this.rotation.length()) {
  16294. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16295. }
  16296. },
  16297. enumerable: true,
  16298. configurable: true
  16299. });
  16300. /**
  16301. * Returns the latest update of the World matrix
  16302. * Returns a Matrix.
  16303. */
  16304. TransformNode.prototype.getWorldMatrix = function () {
  16305. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16306. this.computeWorldMatrix();
  16307. }
  16308. return this._worldMatrix;
  16309. };
  16310. /**
  16311. * Returns the latest update of the World matrix determinant.
  16312. */
  16313. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16314. return this._worldMatrixDeterminant;
  16315. };
  16316. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16317. /**
  16318. * Returns directly the latest state of the mesh World matrix.
  16319. * A Matrix is returned.
  16320. */
  16321. get: function () {
  16322. return this._worldMatrix;
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. /**
  16328. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16329. * Returns the AbstractMesh.
  16330. */
  16331. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16332. this._poseMatrix.copyFrom(matrix);
  16333. return this;
  16334. };
  16335. /**
  16336. * Returns the mesh Pose matrix.
  16337. * Returned object : Matrix
  16338. */
  16339. TransformNode.prototype.getPoseMatrix = function () {
  16340. return this._poseMatrix;
  16341. };
  16342. TransformNode.prototype._isSynchronized = function () {
  16343. if (this._isDirty) {
  16344. return false;
  16345. }
  16346. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16347. return false;
  16348. if (this._cache.pivotMatrixUpdated) {
  16349. return false;
  16350. }
  16351. if (this.infiniteDistance) {
  16352. return false;
  16353. }
  16354. if (!this._cache.position.equals(this.position))
  16355. return false;
  16356. if (this.rotationQuaternion) {
  16357. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16358. return false;
  16359. }
  16360. if (!this._cache.rotation.equals(this.rotation))
  16361. return false;
  16362. if (!this._cache.scaling.equals(this.scaling))
  16363. return false;
  16364. return true;
  16365. };
  16366. TransformNode.prototype._initCache = function () {
  16367. _super.prototype._initCache.call(this);
  16368. this._cache.localMatrixUpdated = false;
  16369. this._cache.position = BABYLON.Vector3.Zero();
  16370. this._cache.scaling = BABYLON.Vector3.Zero();
  16371. this._cache.rotation = BABYLON.Vector3.Zero();
  16372. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16373. this._cache.billboardMode = -1;
  16374. };
  16375. TransformNode.prototype.markAsDirty = function (property) {
  16376. if (property === "rotation") {
  16377. this.rotationQuaternion = null;
  16378. }
  16379. this._currentRenderId = Number.MAX_VALUE;
  16380. this._isDirty = true;
  16381. return this;
  16382. };
  16383. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16384. /**
  16385. * Returns the current mesh absolute position.
  16386. * Retuns a Vector3.
  16387. */
  16388. get: function () {
  16389. return this._absolutePosition;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. /**
  16395. * Sets a new matrix to apply before all other transformation
  16396. * @param matrix defines the transform matrix
  16397. * @returns the current TransformNode
  16398. */
  16399. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16400. return this.setPivotMatrix(matrix, false);
  16401. };
  16402. /**
  16403. * Sets a new pivot matrix to the current node
  16404. * @param matrix defines the new pivot matrix to use
  16405. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16406. * @returns the current TransformNode
  16407. */
  16408. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16409. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16410. this._pivotMatrix = matrix.clone();
  16411. this._cache.pivotMatrixUpdated = true;
  16412. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16413. if (this._postMultiplyPivotMatrix) {
  16414. if (!this._pivotMatrixInverse) {
  16415. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16416. }
  16417. else {
  16418. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16419. }
  16420. }
  16421. return this;
  16422. };
  16423. /**
  16424. * Returns the mesh pivot matrix.
  16425. * Default : Identity.
  16426. * A Matrix is returned.
  16427. */
  16428. TransformNode.prototype.getPivotMatrix = function () {
  16429. return this._pivotMatrix;
  16430. };
  16431. /**
  16432. * Prevents the World matrix to be computed any longer.
  16433. * Returns the AbstractMesh.
  16434. */
  16435. TransformNode.prototype.freezeWorldMatrix = function () {
  16436. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16437. this.computeWorldMatrix(true);
  16438. this._isWorldMatrixFrozen = true;
  16439. return this;
  16440. };
  16441. /**
  16442. * Allows back the World matrix computation.
  16443. * Returns the AbstractMesh.
  16444. */
  16445. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16446. this._isWorldMatrixFrozen = false;
  16447. this.computeWorldMatrix(true);
  16448. return this;
  16449. };
  16450. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16451. /**
  16452. * True if the World matrix has been frozen.
  16453. * Returns a boolean.
  16454. */
  16455. get: function () {
  16456. return this._isWorldMatrixFrozen;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. /**
  16462. * Retuns the mesh absolute position in the World.
  16463. * Returns a Vector3.
  16464. */
  16465. TransformNode.prototype.getAbsolutePosition = function () {
  16466. this.computeWorldMatrix();
  16467. return this._absolutePosition;
  16468. };
  16469. /**
  16470. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16471. * Returns the AbstractMesh.
  16472. */
  16473. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16474. if (!absolutePosition) {
  16475. return this;
  16476. }
  16477. var absolutePositionX;
  16478. var absolutePositionY;
  16479. var absolutePositionZ;
  16480. if (absolutePosition.x === undefined) {
  16481. if (arguments.length < 3) {
  16482. return this;
  16483. }
  16484. absolutePositionX = arguments[0];
  16485. absolutePositionY = arguments[1];
  16486. absolutePositionZ = arguments[2];
  16487. }
  16488. else {
  16489. absolutePositionX = absolutePosition.x;
  16490. absolutePositionY = absolutePosition.y;
  16491. absolutePositionZ = absolutePosition.z;
  16492. }
  16493. if (this.parent) {
  16494. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16495. invertParentWorldMatrix.invert();
  16496. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16497. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16498. }
  16499. else {
  16500. this.position.x = absolutePositionX;
  16501. this.position.y = absolutePositionY;
  16502. this.position.z = absolutePositionZ;
  16503. }
  16504. return this;
  16505. };
  16506. /**
  16507. * Sets the mesh position in its local space.
  16508. * Returns the AbstractMesh.
  16509. */
  16510. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16511. this.computeWorldMatrix();
  16512. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16513. return this;
  16514. };
  16515. /**
  16516. * Returns the mesh position in the local space from the current World matrix values.
  16517. * Returns a new Vector3.
  16518. */
  16519. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16520. this.computeWorldMatrix();
  16521. var invLocalWorldMatrix = this._localWorld.clone();
  16522. invLocalWorldMatrix.invert();
  16523. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16524. };
  16525. /**
  16526. * Translates the mesh along the passed Vector3 in its local space.
  16527. * Returns the AbstractMesh.
  16528. */
  16529. TransformNode.prototype.locallyTranslate = function (vector3) {
  16530. this.computeWorldMatrix(true);
  16531. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16532. return this;
  16533. };
  16534. /**
  16535. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16536. * @param targetPoint the position (must be in same space as current mesh) to look at
  16537. * @param yawCor optional yaw (y-axis) correction in radians
  16538. * @param pitchCor optional pitch (x-axis) correction in radians
  16539. * @param rollCor optional roll (z-axis) correction in radians
  16540. * @param space the choosen space of the target
  16541. * @returns the TransformNode.
  16542. */
  16543. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16544. if (yawCor === void 0) { yawCor = 0; }
  16545. if (pitchCor === void 0) { pitchCor = 0; }
  16546. if (rollCor === void 0) { rollCor = 0; }
  16547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16548. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16549. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16550. targetPoint.subtractToRef(pos, dv);
  16551. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16552. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16553. var pitch = Math.atan2(dv.y, len);
  16554. if (this.rotationQuaternion) {
  16555. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16556. }
  16557. else {
  16558. this.rotation.x = pitch + pitchCor;
  16559. this.rotation.y = yaw + yawCor;
  16560. this.rotation.z = rollCor;
  16561. }
  16562. return this;
  16563. };
  16564. /**
  16565. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16566. * This Vector3 is expressed in the World space.
  16567. */
  16568. TransformNode.prototype.getDirection = function (localAxis) {
  16569. var result = BABYLON.Vector3.Zero();
  16570. this.getDirectionToRef(localAxis, result);
  16571. return result;
  16572. };
  16573. /**
  16574. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16575. * localAxis is expressed in the mesh local space.
  16576. * result is computed in the Wordl space from the mesh World matrix.
  16577. * Returns the AbstractMesh.
  16578. */
  16579. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16580. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16581. return this;
  16582. };
  16583. /**
  16584. * Sets a new pivot point to the current node
  16585. * @param point defines the new pivot point to use
  16586. * @param space defines if the point is in world or local space (local by default)
  16587. * @returns the current TransformNode
  16588. */
  16589. TransformNode.prototype.setPivotPoint = function (point, space) {
  16590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16591. if (this.getScene().getRenderId() == 0) {
  16592. this.computeWorldMatrix(true);
  16593. }
  16594. var wm = this.getWorldMatrix();
  16595. if (space == BABYLON.Space.WORLD) {
  16596. var tmat = BABYLON.Tmp.Matrix[0];
  16597. wm.invertToRef(tmat);
  16598. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16599. }
  16600. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16601. };
  16602. /**
  16603. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16604. */
  16605. TransformNode.prototype.getPivotPoint = function () {
  16606. var point = BABYLON.Vector3.Zero();
  16607. this.getPivotPointToRef(point);
  16608. return point;
  16609. };
  16610. /**
  16611. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16612. * Returns the AbstractMesh.
  16613. */
  16614. TransformNode.prototype.getPivotPointToRef = function (result) {
  16615. result.x = -this._pivotMatrix.m[12];
  16616. result.y = -this._pivotMatrix.m[13];
  16617. result.z = -this._pivotMatrix.m[14];
  16618. return this;
  16619. };
  16620. /**
  16621. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16622. */
  16623. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16624. var point = BABYLON.Vector3.Zero();
  16625. this.getAbsolutePivotPointToRef(point);
  16626. return point;
  16627. };
  16628. /**
  16629. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16630. * Returns the AbstractMesh.
  16631. */
  16632. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16633. result.x = this._pivotMatrix.m[12];
  16634. result.y = this._pivotMatrix.m[13];
  16635. result.z = this._pivotMatrix.m[14];
  16636. this.getPivotPointToRef(result);
  16637. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16638. return this;
  16639. };
  16640. /**
  16641. * Defines the passed node as the parent of the current node.
  16642. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16643. * Returns the TransformNode.
  16644. */
  16645. TransformNode.prototype.setParent = function (node) {
  16646. if (node === null) {
  16647. var rotation = BABYLON.Tmp.Quaternion[0];
  16648. var position = BABYLON.Tmp.Vector3[0];
  16649. var scale = BABYLON.Tmp.Vector3[1];
  16650. if (this.parent && this.parent.computeWorldMatrix) {
  16651. this.parent.computeWorldMatrix(true);
  16652. }
  16653. this.computeWorldMatrix(true);
  16654. this.getWorldMatrix().decompose(scale, rotation, position);
  16655. if (this.rotationQuaternion) {
  16656. this.rotationQuaternion.copyFrom(rotation);
  16657. }
  16658. else {
  16659. rotation.toEulerAnglesToRef(this.rotation);
  16660. }
  16661. this.scaling.x = scale.x;
  16662. this.scaling.y = scale.y;
  16663. this.scaling.z = scale.z;
  16664. this.position.x = position.x;
  16665. this.position.y = position.y;
  16666. this.position.z = position.z;
  16667. }
  16668. else {
  16669. var rotation = BABYLON.Tmp.Quaternion[0];
  16670. var position = BABYLON.Tmp.Vector3[0];
  16671. var scale = BABYLON.Tmp.Vector3[1];
  16672. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16673. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16674. this.computeWorldMatrix(true);
  16675. node.computeWorldMatrix(true);
  16676. node.getWorldMatrix().invertToRef(invParentMatrix);
  16677. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16678. diffMatrix.decompose(scale, rotation, position);
  16679. if (this.rotationQuaternion) {
  16680. this.rotationQuaternion.copyFrom(rotation);
  16681. }
  16682. else {
  16683. rotation.toEulerAnglesToRef(this.rotation);
  16684. }
  16685. this.position.x = position.x;
  16686. this.position.y = position.y;
  16687. this.position.z = position.z;
  16688. this.scaling.x = scale.x;
  16689. this.scaling.y = scale.y;
  16690. this.scaling.z = scale.z;
  16691. }
  16692. this.parent = node;
  16693. return this;
  16694. };
  16695. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16696. get: function () {
  16697. return this._nonUniformScaling;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16703. if (this._nonUniformScaling === value) {
  16704. return false;
  16705. }
  16706. this._nonUniformScaling = true;
  16707. return true;
  16708. };
  16709. /**
  16710. * Attach the current TransformNode to another TransformNode associated with a bone
  16711. * @param bone Bone affecting the TransformNode
  16712. * @param affectedTransformNode TransformNode associated with the bone
  16713. */
  16714. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16715. this._transformToBoneReferal = affectedTransformNode;
  16716. this.parent = bone;
  16717. if (bone.getWorldMatrix().determinant() < 0) {
  16718. this.scalingDeterminant *= -1;
  16719. }
  16720. return this;
  16721. };
  16722. TransformNode.prototype.detachFromBone = function () {
  16723. if (!this.parent) {
  16724. return this;
  16725. }
  16726. if (this.parent.getWorldMatrix().determinant() < 0) {
  16727. this.scalingDeterminant *= -1;
  16728. }
  16729. this._transformToBoneReferal = null;
  16730. this.parent = null;
  16731. return this;
  16732. };
  16733. /**
  16734. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16735. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16736. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16737. * The passed axis is also normalized.
  16738. * Returns the AbstractMesh.
  16739. */
  16740. TransformNode.prototype.rotate = function (axis, amount, space) {
  16741. axis.normalize();
  16742. if (!this.rotationQuaternion) {
  16743. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16744. this.rotation = BABYLON.Vector3.Zero();
  16745. }
  16746. var rotationQuaternion;
  16747. if (!space || space === BABYLON.Space.LOCAL) {
  16748. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16749. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16750. }
  16751. else {
  16752. if (this.parent) {
  16753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16754. invertParentWorldMatrix.invert();
  16755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16756. }
  16757. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16758. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16764. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16765. * The passed axis is also normalized.
  16766. * Returns the AbstractMesh.
  16767. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16768. */
  16769. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16770. axis.normalize();
  16771. if (!this.rotationQuaternion) {
  16772. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16773. this.rotation.copyFromFloats(0, 0, 0);
  16774. }
  16775. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16776. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16777. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16778. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16779. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16780. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16781. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16782. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16783. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16784. return this;
  16785. };
  16786. /**
  16787. * Translates the mesh along the axis vector for the passed distance in the given space.
  16788. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16789. * Returns the AbstractMesh.
  16790. */
  16791. TransformNode.prototype.translate = function (axis, distance, space) {
  16792. var displacementVector = axis.scale(distance);
  16793. if (!space || space === BABYLON.Space.LOCAL) {
  16794. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16795. this.setPositionWithLocalVector(tempV3);
  16796. }
  16797. else {
  16798. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16799. }
  16800. return this;
  16801. };
  16802. /**
  16803. * Adds a rotation step to the mesh current rotation.
  16804. * x, y, z are Euler angles expressed in radians.
  16805. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16806. * This means this rotation is made in the mesh local space only.
  16807. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16808. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16809. * ```javascript
  16810. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16811. * ```
  16812. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16813. * 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.
  16814. * Returns the AbstractMesh.
  16815. */
  16816. TransformNode.prototype.addRotation = function (x, y, z) {
  16817. var rotationQuaternion;
  16818. if (this.rotationQuaternion) {
  16819. rotationQuaternion = this.rotationQuaternion;
  16820. }
  16821. else {
  16822. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16823. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16824. }
  16825. var accumulation = BABYLON.Tmp.Quaternion[0];
  16826. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16827. rotationQuaternion.multiplyInPlace(accumulation);
  16828. if (!this.rotationQuaternion) {
  16829. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16830. }
  16831. return this;
  16832. };
  16833. /**
  16834. * Computes the mesh World matrix and returns it.
  16835. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16836. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16837. * If the parameter `force`is set to `true`, the actual computation is done.
  16838. * Returns the mesh World Matrix.
  16839. */
  16840. TransformNode.prototype.computeWorldMatrix = function (force) {
  16841. if (this._isWorldMatrixFrozen) {
  16842. return this._worldMatrix;
  16843. }
  16844. if (!force && this.isSynchronized(true)) {
  16845. return this._worldMatrix;
  16846. }
  16847. this._cache.position.copyFrom(this.position);
  16848. this._cache.scaling.copyFrom(this.scaling);
  16849. this._cache.pivotMatrixUpdated = false;
  16850. this._cache.billboardMode = this.billboardMode;
  16851. this._currentRenderId = this.getScene().getRenderId();
  16852. this._isDirty = false;
  16853. // Scaling
  16854. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16855. // Rotation
  16856. //rotate, if quaternion is set and rotation was used
  16857. if (this.rotationQuaternion) {
  16858. var len = this.rotation.length();
  16859. if (len) {
  16860. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16861. this.rotation.copyFromFloats(0, 0, 0);
  16862. }
  16863. }
  16864. if (this.rotationQuaternion) {
  16865. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16866. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16867. }
  16868. else {
  16869. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16870. this._cache.rotation.copyFrom(this.rotation);
  16871. }
  16872. // Translation
  16873. var camera = this.getScene().activeCamera;
  16874. if (this.infiniteDistance && !this.parent && camera) {
  16875. var cameraWorldMatrix = camera.getWorldMatrix();
  16876. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16877. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16878. }
  16879. else {
  16880. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16881. }
  16882. // Composing transformations
  16883. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16884. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16885. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16886. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16887. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16888. // Need to decompose each rotation here
  16889. var currentPosition = BABYLON.Tmp.Vector3[3];
  16890. if (this.parent && this.parent.getWorldMatrix) {
  16891. if (this._transformToBoneReferal) {
  16892. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16893. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16894. }
  16895. else {
  16896. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16897. }
  16898. }
  16899. else {
  16900. currentPosition.copyFrom(this.position);
  16901. }
  16902. currentPosition.subtractInPlace(camera.globalPosition);
  16903. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16904. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16905. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16906. }
  16907. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16908. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16909. }
  16910. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16911. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16912. }
  16913. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16914. }
  16915. else {
  16916. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16917. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16918. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16919. }
  16920. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16921. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16922. }
  16923. // Local world
  16924. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16925. // Parent
  16926. if (this.parent && this.parent.getWorldMatrix) {
  16927. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16928. if (this._transformToBoneReferal) {
  16929. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16930. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16931. }
  16932. else {
  16933. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16934. }
  16935. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16936. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16937. this._worldMatrix.copyFrom(this._localWorld);
  16938. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16939. }
  16940. else {
  16941. if (this._transformToBoneReferal) {
  16942. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16943. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16944. }
  16945. else {
  16946. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16947. }
  16948. }
  16949. this._markSyncedWithParent();
  16950. }
  16951. else {
  16952. this._worldMatrix.copyFrom(this._localWorld);
  16953. }
  16954. // Post multiply inverse of pivotMatrix
  16955. if (this._postMultiplyPivotMatrix) {
  16956. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16957. }
  16958. // Normal matrix
  16959. if (this.scaling.isNonUniform) {
  16960. this._updateNonUniformScalingState(true);
  16961. }
  16962. else if (this.parent && this.parent._nonUniformScaling) {
  16963. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16964. }
  16965. else {
  16966. this._updateNonUniformScalingState(false);
  16967. }
  16968. this._afterComputeWorldMatrix();
  16969. // Absolute position
  16970. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16971. // Callbacks
  16972. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16973. if (!this._poseMatrix) {
  16974. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16975. }
  16976. // Cache the determinant
  16977. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16978. return this._worldMatrix;
  16979. };
  16980. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16981. };
  16982. /**
  16983. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16984. * @param func: callback function to add
  16985. *
  16986. * Returns the TransformNode.
  16987. */
  16988. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16989. this.onAfterWorldMatrixUpdateObservable.add(func);
  16990. return this;
  16991. };
  16992. /**
  16993. * Removes a registered callback function.
  16994. * Returns the TransformNode.
  16995. */
  16996. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16997. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16998. return this;
  16999. };
  17000. /**
  17001. * Clone the current transform node
  17002. * Returns the new transform node
  17003. * @param name Name of the new clone
  17004. * @param newParent New parent for the clone
  17005. * @param doNotCloneChildren Do not clone children hierarchy
  17006. */
  17007. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17008. var _this = this;
  17009. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17010. result.name = name;
  17011. result.id = name;
  17012. if (newParent) {
  17013. result.parent = newParent;
  17014. }
  17015. if (!doNotCloneChildren) {
  17016. // Children
  17017. var directDescendants = this.getDescendants(true);
  17018. for (var index = 0; index < directDescendants.length; index++) {
  17019. var child = directDescendants[index];
  17020. if (child.clone) {
  17021. child.clone(name + "." + child.name, result);
  17022. }
  17023. }
  17024. }
  17025. return result;
  17026. };
  17027. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17028. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17029. serializationObject.type = this.getClassName();
  17030. // Parent
  17031. if (this.parent) {
  17032. serializationObject.parentId = this.parent.id;
  17033. }
  17034. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17035. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17036. }
  17037. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17038. serializationObject.isEnabled = this.isEnabled();
  17039. // Parent
  17040. if (this.parent) {
  17041. serializationObject.parentId = this.parent.id;
  17042. }
  17043. return serializationObject;
  17044. };
  17045. // Statics
  17046. /**
  17047. * Returns a new TransformNode object parsed from the source provided.
  17048. * The parameter `parsedMesh` is the source.
  17049. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17050. */
  17051. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17052. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17053. if (BABYLON.Tags) {
  17054. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17055. }
  17056. if (parsedTransformNode.localMatrix) {
  17057. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17058. }
  17059. else if (parsedTransformNode.pivotMatrix) {
  17060. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17061. }
  17062. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17063. // Parent
  17064. if (parsedTransformNode.parentId) {
  17065. transformNode._waitingParentId = parsedTransformNode.parentId;
  17066. }
  17067. return transformNode;
  17068. };
  17069. /**
  17070. * Disposes the TransformNode.
  17071. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17072. * Returns nothing.
  17073. */
  17074. TransformNode.prototype.dispose = function (doNotRecurse) {
  17075. // Animations
  17076. this.getScene().stopAnimation(this);
  17077. // Remove from scene
  17078. this.getScene().removeTransformNode(this);
  17079. if (!doNotRecurse) {
  17080. // Children
  17081. var objects = this.getDescendants(true);
  17082. for (var index = 0; index < objects.length; index++) {
  17083. objects[index].dispose();
  17084. }
  17085. }
  17086. else {
  17087. var childMeshes = this.getChildMeshes(true);
  17088. for (index = 0; index < childMeshes.length; index++) {
  17089. var child = childMeshes[index];
  17090. child.parent = null;
  17091. child.computeWorldMatrix(true);
  17092. }
  17093. }
  17094. this.onAfterWorldMatrixUpdateObservable.clear();
  17095. _super.prototype.dispose.call(this);
  17096. };
  17097. // Statics
  17098. TransformNode.BILLBOARDMODE_NONE = 0;
  17099. TransformNode.BILLBOARDMODE_X = 1;
  17100. TransformNode.BILLBOARDMODE_Y = 2;
  17101. TransformNode.BILLBOARDMODE_Z = 4;
  17102. TransformNode.BILLBOARDMODE_ALL = 7;
  17103. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17104. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17105. __decorate([
  17106. BABYLON.serializeAsVector3()
  17107. ], TransformNode.prototype, "_rotation", void 0);
  17108. __decorate([
  17109. BABYLON.serializeAsQuaternion()
  17110. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17111. __decorate([
  17112. BABYLON.serializeAsVector3()
  17113. ], TransformNode.prototype, "_scaling", void 0);
  17114. __decorate([
  17115. BABYLON.serialize()
  17116. ], TransformNode.prototype, "billboardMode", void 0);
  17117. __decorate([
  17118. BABYLON.serialize()
  17119. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17120. __decorate([
  17121. BABYLON.serialize()
  17122. ], TransformNode.prototype, "infiniteDistance", void 0);
  17123. __decorate([
  17124. BABYLON.serializeAsVector3()
  17125. ], TransformNode.prototype, "position", void 0);
  17126. return TransformNode;
  17127. }(BABYLON.Node));
  17128. BABYLON.TransformNode = TransformNode;
  17129. })(BABYLON || (BABYLON = {}));
  17130. //# sourceMappingURL=babylon.transformNode.js.map
  17131. var BABYLON;
  17132. (function (BABYLON) {
  17133. var AbstractMesh = /** @class */ (function (_super) {
  17134. __extends(AbstractMesh, _super);
  17135. // Constructor
  17136. function AbstractMesh(name, scene) {
  17137. if (scene === void 0) { scene = null; }
  17138. var _this = _super.call(this, name, scene, false) || this;
  17139. _this._facetNb = 0; // facet number
  17140. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17141. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17142. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17143. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17144. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17145. _this._subDiv = {
  17146. max: 1,
  17147. X: 1,
  17148. Y: 1,
  17149. Z: 1
  17150. };
  17151. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17152. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17153. // Events
  17154. /**
  17155. * An event triggered when this mesh collides with another one
  17156. * @type {BABYLON.Observable}
  17157. */
  17158. _this.onCollideObservable = new BABYLON.Observable();
  17159. /**
  17160. * An event triggered when the collision's position changes
  17161. * @type {BABYLON.Observable}
  17162. */
  17163. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17164. /**
  17165. * An event triggered when material is changed
  17166. * @type {BABYLON.Observable}
  17167. */
  17168. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17169. // Properties
  17170. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17171. /**
  17172. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17173. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17174. * or
  17175. * 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.
  17176. * for more info check WebGl documentations
  17177. */
  17178. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17179. /**
  17180. * 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:
  17181. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17182. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17183. * 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.
  17184. */
  17185. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17186. /**
  17187. * 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.
  17188. * The default value is -1 which means don't break the query and wait till the result.
  17189. */
  17190. _this.occlusionRetryCount = -1;
  17191. _this._occlusionInternalRetryCounter = 0;
  17192. _this._isOccluded = false;
  17193. _this._isOcclusionQueryInProgress = false;
  17194. _this._visibility = 1.0;
  17195. _this.alphaIndex = Number.MAX_VALUE;
  17196. _this.isVisible = true;
  17197. _this.isPickable = true;
  17198. _this.showBoundingBox = false;
  17199. _this.showSubMeshesBoundingBox = false;
  17200. _this.isBlocker = false;
  17201. _this.enablePointerMoveEvents = false;
  17202. _this.renderingGroupId = 0;
  17203. _this._receiveShadows = false;
  17204. _this.renderOutline = false;
  17205. _this.outlineColor = BABYLON.Color3.Red();
  17206. _this.outlineWidth = 0.02;
  17207. _this.renderOverlay = false;
  17208. _this.overlayColor = BABYLON.Color3.Red();
  17209. _this.overlayAlpha = 0.5;
  17210. _this._hasVertexAlpha = false;
  17211. _this._useVertexColors = true;
  17212. _this._computeBonesUsingShaders = true;
  17213. _this._numBoneInfluencers = 4;
  17214. _this._applyFog = true;
  17215. _this.useOctreeForRenderingSelection = true;
  17216. _this.useOctreeForPicking = true;
  17217. _this.useOctreeForCollisions = true;
  17218. _this._layerMask = 0x0FFFFFFF;
  17219. /**
  17220. * True if the mesh must be rendered in any case.
  17221. */
  17222. _this.alwaysSelectAsActiveMesh = false;
  17223. /**
  17224. * This scene's action manager
  17225. * @type {BABYLON.ActionManager}
  17226. */
  17227. _this.actionManager = null;
  17228. // Physics
  17229. _this.physicsImpostor = null;
  17230. // Collisions
  17231. _this._checkCollisions = false;
  17232. _this._collisionMask = -1;
  17233. _this._collisionGroup = -1;
  17234. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17235. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17236. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17237. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17238. // Edges
  17239. _this.edgesWidth = 1;
  17240. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17241. // Cache
  17242. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17243. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17244. _this._renderId = 0;
  17245. _this._intersectionsInProgress = new Array();
  17246. _this._unIndexed = false;
  17247. _this._lightSources = new Array();
  17248. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17249. if (collidedMesh === void 0) { collidedMesh = null; }
  17250. //TODO move this to the collision coordinator!
  17251. if (_this.getScene().workerCollisions)
  17252. newPosition.multiplyInPlace(_this._collider._radius);
  17253. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17254. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17255. _this.position.addInPlace(_this._diffPositionForCollisions);
  17256. }
  17257. if (collidedMesh) {
  17258. _this.onCollideObservable.notifyObservers(collidedMesh);
  17259. }
  17260. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17261. };
  17262. _this.getScene().addMesh(_this);
  17263. _this._resyncLightSources();
  17264. return _this;
  17265. }
  17266. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17267. get: function () {
  17268. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17269. },
  17270. enumerable: true,
  17271. configurable: true
  17272. });
  17273. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17274. get: function () {
  17275. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17281. get: function () {
  17282. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17288. get: function () {
  17289. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17290. },
  17291. enumerable: true,
  17292. configurable: true
  17293. });
  17294. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17295. get: function () {
  17296. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17297. },
  17298. enumerable: true,
  17299. configurable: true
  17300. });
  17301. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17302. /**
  17303. * Read-only : the number of facets in the mesh
  17304. */
  17305. get: function () {
  17306. return this._facetNb;
  17307. },
  17308. enumerable: true,
  17309. configurable: true
  17310. });
  17311. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17312. /**
  17313. * The number (integer) of subdivisions per axis in the partioning space
  17314. */
  17315. get: function () {
  17316. return this._partitioningSubdivisions;
  17317. },
  17318. set: function (nb) {
  17319. this._partitioningSubdivisions = nb;
  17320. },
  17321. enumerable: true,
  17322. configurable: true
  17323. });
  17324. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17325. /**
  17326. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17327. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17328. */
  17329. get: function () {
  17330. return this._partitioningBBoxRatio;
  17331. },
  17332. set: function (ratio) {
  17333. this._partitioningBBoxRatio = ratio;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17339. /**
  17340. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17341. * Works only for updatable meshes.
  17342. * Doesn't work with multi-materials.
  17343. */
  17344. get: function () {
  17345. return this._facetDepthSort;
  17346. },
  17347. set: function (sort) {
  17348. this._facetDepthSort = sort;
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17354. /**
  17355. * The location (Vector3) where the facet depth sort must be computed from.
  17356. * By default, the active camera position.
  17357. * Used only when facet depth sort is enabled.
  17358. */
  17359. get: function () {
  17360. return this._facetDepthSortFrom;
  17361. },
  17362. set: function (location) {
  17363. this._facetDepthSortFrom = location;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17369. /**
  17370. * Read-only boolean : is the feature facetData enabled ?
  17371. */
  17372. get: function () {
  17373. return this._facetDataEnabled;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17379. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17380. return false;
  17381. }
  17382. this._markSubMeshesAsMiscDirty();
  17383. return true;
  17384. };
  17385. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17386. set: function (callback) {
  17387. if (this._onCollideObserver) {
  17388. this.onCollideObservable.remove(this._onCollideObserver);
  17389. }
  17390. this._onCollideObserver = this.onCollideObservable.add(callback);
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17396. set: function (callback) {
  17397. if (this._onCollisionPositionChangeObserver) {
  17398. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17399. }
  17400. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17401. },
  17402. enumerable: true,
  17403. configurable: true
  17404. });
  17405. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17406. /**
  17407. * 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.
  17408. */
  17409. get: function () {
  17410. return this._isOccluded;
  17411. },
  17412. set: function (value) {
  17413. this._isOccluded = value;
  17414. },
  17415. enumerable: true,
  17416. configurable: true
  17417. });
  17418. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17419. /**
  17420. * Flag to check the progress status of the query
  17421. */
  17422. get: function () {
  17423. return this._isOcclusionQueryInProgress;
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17429. /**
  17430. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17431. */
  17432. get: function () {
  17433. return this._visibility;
  17434. },
  17435. /**
  17436. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17437. */
  17438. set: function (value) {
  17439. if (this._visibility === value) {
  17440. return;
  17441. }
  17442. this._visibility = value;
  17443. this._markSubMeshesAsMiscDirty();
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. Object.defineProperty(AbstractMesh.prototype, "material", {
  17449. get: function () {
  17450. return this._material;
  17451. },
  17452. set: function (value) {
  17453. if (this._material === value) {
  17454. return;
  17455. }
  17456. this._material = value;
  17457. if (this.onMaterialChangedObservable.hasObservers) {
  17458. this.onMaterialChangedObservable.notifyObservers(this);
  17459. }
  17460. if (!this.subMeshes) {
  17461. return;
  17462. }
  17463. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17464. var subMesh = _a[_i];
  17465. subMesh.setEffect(null);
  17466. }
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17472. get: function () {
  17473. return this._receiveShadows;
  17474. },
  17475. set: function (value) {
  17476. if (this._receiveShadows === value) {
  17477. return;
  17478. }
  17479. this._receiveShadows = value;
  17480. this._markSubMeshesAsLightDirty();
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17486. get: function () {
  17487. return this._hasVertexAlpha;
  17488. },
  17489. set: function (value) {
  17490. if (this._hasVertexAlpha === value) {
  17491. return;
  17492. }
  17493. this._hasVertexAlpha = value;
  17494. this._markSubMeshesAsAttributesDirty();
  17495. this._markSubMeshesAsMiscDirty();
  17496. },
  17497. enumerable: true,
  17498. configurable: true
  17499. });
  17500. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17501. get: function () {
  17502. return this._useVertexColors;
  17503. },
  17504. set: function (value) {
  17505. if (this._useVertexColors === value) {
  17506. return;
  17507. }
  17508. this._useVertexColors = value;
  17509. this._markSubMeshesAsAttributesDirty();
  17510. },
  17511. enumerable: true,
  17512. configurable: true
  17513. });
  17514. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17515. get: function () {
  17516. return this._computeBonesUsingShaders;
  17517. },
  17518. set: function (value) {
  17519. if (this._computeBonesUsingShaders === value) {
  17520. return;
  17521. }
  17522. this._computeBonesUsingShaders = value;
  17523. this._markSubMeshesAsAttributesDirty();
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17529. get: function () {
  17530. return this._numBoneInfluencers;
  17531. },
  17532. set: function (value) {
  17533. if (this._numBoneInfluencers === value) {
  17534. return;
  17535. }
  17536. this._numBoneInfluencers = value;
  17537. this._markSubMeshesAsAttributesDirty();
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17543. get: function () {
  17544. return this._applyFog;
  17545. },
  17546. set: function (value) {
  17547. if (this._applyFog === value) {
  17548. return;
  17549. }
  17550. this._applyFog = value;
  17551. this._markSubMeshesAsMiscDirty();
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17557. get: function () {
  17558. return this._layerMask;
  17559. },
  17560. set: function (value) {
  17561. if (value === this._layerMask) {
  17562. return;
  17563. }
  17564. this._layerMask = value;
  17565. this._resyncLightSources();
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17571. get: function () {
  17572. return this._collisionMask;
  17573. },
  17574. set: function (mask) {
  17575. this._collisionMask = !isNaN(mask) ? mask : -1;
  17576. },
  17577. enumerable: true,
  17578. configurable: true
  17579. });
  17580. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17581. get: function () {
  17582. return this._collisionGroup;
  17583. },
  17584. set: function (mask) {
  17585. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17591. get: function () {
  17592. return null;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17598. get: function () {
  17599. return this._skeleton;
  17600. },
  17601. set: function (value) {
  17602. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17603. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17604. }
  17605. if (value && value.needInitialSkinMatrix) {
  17606. value._registerMeshWithPoseMatrix(this);
  17607. }
  17608. this._skeleton = value;
  17609. if (!this._skeleton) {
  17610. this._bonesTransformMatrices = null;
  17611. }
  17612. this._markSubMeshesAsAttributesDirty();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. /**
  17618. * Returns the string "AbstractMesh"
  17619. */
  17620. AbstractMesh.prototype.getClassName = function () {
  17621. return "AbstractMesh";
  17622. };
  17623. /**
  17624. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17625. */
  17626. AbstractMesh.prototype.toString = function (fullDetails) {
  17627. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17628. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17629. if (this._skeleton) {
  17630. ret += ", skeleton: " + this._skeleton.name;
  17631. }
  17632. if (fullDetails) {
  17633. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17634. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17635. }
  17636. return ret;
  17637. };
  17638. AbstractMesh.prototype._rebuild = function () {
  17639. if (this._occlusionQuery) {
  17640. this._occlusionQuery = null;
  17641. }
  17642. if (this._edgesRenderer) {
  17643. this._edgesRenderer._rebuild();
  17644. }
  17645. if (!this.subMeshes) {
  17646. return;
  17647. }
  17648. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17649. var subMesh = _a[_i];
  17650. subMesh._rebuild();
  17651. }
  17652. };
  17653. AbstractMesh.prototype._resyncLightSources = function () {
  17654. this._lightSources.length = 0;
  17655. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17656. var light = _a[_i];
  17657. if (!light.isEnabled()) {
  17658. continue;
  17659. }
  17660. if (light.canAffectMesh(this)) {
  17661. this._lightSources.push(light);
  17662. }
  17663. }
  17664. this._markSubMeshesAsLightDirty();
  17665. };
  17666. AbstractMesh.prototype._resyncLighSource = function (light) {
  17667. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17668. var index = this._lightSources.indexOf(light);
  17669. if (index === -1) {
  17670. if (!isIn) {
  17671. return;
  17672. }
  17673. this._lightSources.push(light);
  17674. }
  17675. else {
  17676. if (isIn) {
  17677. return;
  17678. }
  17679. this._lightSources.splice(index, 1);
  17680. }
  17681. this._markSubMeshesAsLightDirty();
  17682. };
  17683. AbstractMesh.prototype._removeLightSource = function (light) {
  17684. var index = this._lightSources.indexOf(light);
  17685. if (index === -1) {
  17686. return;
  17687. }
  17688. this._lightSources.splice(index, 1);
  17689. this._markSubMeshesAsLightDirty();
  17690. };
  17691. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17692. if (!this.subMeshes) {
  17693. return;
  17694. }
  17695. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17696. var subMesh = _a[_i];
  17697. if (subMesh._materialDefines) {
  17698. func(subMesh._materialDefines);
  17699. }
  17700. }
  17701. };
  17702. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17703. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17704. };
  17705. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17706. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17707. };
  17708. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17709. if (!this.subMeshes) {
  17710. return;
  17711. }
  17712. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17713. var subMesh = _a[_i];
  17714. var material = subMesh.getMaterial();
  17715. if (material) {
  17716. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17717. }
  17718. }
  17719. };
  17720. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17721. /**
  17722. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17723. * Default : (1.0, 1.0, 1.0)
  17724. */
  17725. get: function () {
  17726. return this._scaling;
  17727. },
  17728. /**
  17729. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17730. * Default : (1.0, 1.0, 1.0)
  17731. */
  17732. set: function (newScaling) {
  17733. this._scaling = newScaling;
  17734. if (this.physicsImpostor) {
  17735. this.physicsImpostor.forceUpdate();
  17736. }
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. // Methods
  17742. /**
  17743. * Disables the mesh edger rendering mode.
  17744. * Returns the AbstractMesh.
  17745. */
  17746. AbstractMesh.prototype.disableEdgesRendering = function () {
  17747. if (this._edgesRenderer) {
  17748. this._edgesRenderer.dispose();
  17749. this._edgesRenderer = null;
  17750. }
  17751. return this;
  17752. };
  17753. /**
  17754. * Enables the edge rendering mode on the mesh.
  17755. * This mode makes the mesh edges visible.
  17756. * Returns the AbstractMesh.
  17757. */
  17758. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17759. if (epsilon === void 0) { epsilon = 0.95; }
  17760. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17761. this.disableEdgesRendering();
  17762. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17763. return this;
  17764. };
  17765. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17766. /**
  17767. * Returns true if the mesh is blocked. Used by the class Mesh.
  17768. * Returns the boolean `false` by default.
  17769. */
  17770. get: function () {
  17771. return false;
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. /**
  17777. * Returns the mesh itself by default, used by the class Mesh.
  17778. * Returned type : AbstractMesh
  17779. */
  17780. AbstractMesh.prototype.getLOD = function (camera) {
  17781. return this;
  17782. };
  17783. /**
  17784. * Returns 0 by default, used by the class Mesh.
  17785. * Returns an integer.
  17786. */
  17787. AbstractMesh.prototype.getTotalVertices = function () {
  17788. return 0;
  17789. };
  17790. /**
  17791. * Returns null by default, used by the class Mesh.
  17792. * Returned type : integer array
  17793. */
  17794. AbstractMesh.prototype.getIndices = function () {
  17795. return null;
  17796. };
  17797. /**
  17798. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17799. * Returned type : float array or Float32Array
  17800. */
  17801. AbstractMesh.prototype.getVerticesData = function (kind) {
  17802. return null;
  17803. };
  17804. /**
  17805. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17806. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17807. * The `data` are either a numeric array either a Float32Array.
  17808. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17809. * 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).
  17810. * Note that a new underlying VertexBuffer object is created each call.
  17811. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17812. *
  17813. * Possible `kind` values :
  17814. * - BABYLON.VertexBuffer.PositionKind
  17815. * - BABYLON.VertexBuffer.UVKind
  17816. * - BABYLON.VertexBuffer.UV2Kind
  17817. * - BABYLON.VertexBuffer.UV3Kind
  17818. * - BABYLON.VertexBuffer.UV4Kind
  17819. * - BABYLON.VertexBuffer.UV5Kind
  17820. * - BABYLON.VertexBuffer.UV6Kind
  17821. * - BABYLON.VertexBuffer.ColorKind
  17822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17826. *
  17827. * Returns the Mesh.
  17828. */
  17829. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17830. return this;
  17831. };
  17832. /**
  17833. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17834. * If the mesh has no geometry, it is simply returned as it is.
  17835. * The `data` are either a numeric array either a Float32Array.
  17836. * No new underlying VertexBuffer object is created.
  17837. * 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.
  17838. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17839. *
  17840. * Possible `kind` values :
  17841. * - BABYLON.VertexBuffer.PositionKind
  17842. * - BABYLON.VertexBuffer.UVKind
  17843. * - BABYLON.VertexBuffer.UV2Kind
  17844. * - BABYLON.VertexBuffer.UV3Kind
  17845. * - BABYLON.VertexBuffer.UV4Kind
  17846. * - BABYLON.VertexBuffer.UV5Kind
  17847. * - BABYLON.VertexBuffer.UV6Kind
  17848. * - BABYLON.VertexBuffer.ColorKind
  17849. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17850. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17851. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17852. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17853. *
  17854. * Returns the Mesh.
  17855. */
  17856. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17857. return this;
  17858. };
  17859. /**
  17860. * Sets the mesh indices.
  17861. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17862. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17863. * This method creates a new index buffer each call.
  17864. * Returns the Mesh.
  17865. */
  17866. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17867. return this;
  17868. };
  17869. /** Returns false by default, used by the class Mesh.
  17870. * Returns a boolean
  17871. */
  17872. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17873. return false;
  17874. };
  17875. /**
  17876. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17877. * Returns a BoundingInfo
  17878. */
  17879. AbstractMesh.prototype.getBoundingInfo = function () {
  17880. if (this._masterMesh) {
  17881. return this._masterMesh.getBoundingInfo();
  17882. }
  17883. if (!this._boundingInfo) {
  17884. // this._boundingInfo is being created here
  17885. this._updateBoundingInfo();
  17886. }
  17887. // cannot be null.
  17888. return this._boundingInfo;
  17889. };
  17890. /**
  17891. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17892. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17893. */
  17894. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17895. if (includeDescendants === void 0) { includeDescendants = true; }
  17896. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17897. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17898. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17899. if (maxDimension === 0) {
  17900. return this;
  17901. }
  17902. var scale = 1 / maxDimension;
  17903. this.scaling.scaleInPlace(scale);
  17904. return this;
  17905. };
  17906. /**
  17907. * Sets a mesh new object BoundingInfo.
  17908. * Returns the AbstractMesh.
  17909. */
  17910. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17911. this._boundingInfo = boundingInfo;
  17912. return this;
  17913. };
  17914. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17915. get: function () {
  17916. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. AbstractMesh.prototype._preActivate = function () {
  17922. };
  17923. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17924. };
  17925. AbstractMesh.prototype._activate = function (renderId) {
  17926. this._renderId = renderId;
  17927. };
  17928. /**
  17929. * Returns the latest update of the World matrix
  17930. * Returns a Matrix.
  17931. */
  17932. AbstractMesh.prototype.getWorldMatrix = function () {
  17933. if (this._masterMesh) {
  17934. return this._masterMesh.getWorldMatrix();
  17935. }
  17936. return _super.prototype.getWorldMatrix.call(this);
  17937. };
  17938. /**
  17939. * Returns the latest update of the World matrix determinant.
  17940. */
  17941. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17942. if (this._masterMesh) {
  17943. return this._masterMesh._getWorldMatrixDeterminant();
  17944. }
  17945. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17946. };
  17947. // ================================== Point of View Movement =================================
  17948. /**
  17949. * Perform relative position change from the point of view of behind the front of the mesh.
  17950. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17951. * Supports definition of mesh facing forward or backward.
  17952. * @param {number} amountRight
  17953. * @param {number} amountUp
  17954. * @param {number} amountForward
  17955. *
  17956. * Returns the AbstractMesh.
  17957. */
  17958. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17959. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17960. return this;
  17961. };
  17962. /**
  17963. * Calculate relative position change from the point of view of behind the front of the mesh.
  17964. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17965. * Supports definition of mesh facing forward or backward.
  17966. * @param {number} amountRight
  17967. * @param {number} amountUp
  17968. * @param {number} amountForward
  17969. *
  17970. * Returns a new Vector3.
  17971. */
  17972. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17973. var rotMatrix = new BABYLON.Matrix();
  17974. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17975. rotQuaternion.toRotationMatrix(rotMatrix);
  17976. var translationDelta = BABYLON.Vector3.Zero();
  17977. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17978. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17979. return translationDelta;
  17980. };
  17981. // ================================== Point of View Rotation =================================
  17982. /**
  17983. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17984. * Supports definition of mesh facing forward or backward.
  17985. * @param {number} flipBack
  17986. * @param {number} twirlClockwise
  17987. * @param {number} tiltRight
  17988. *
  17989. * Returns the AbstractMesh.
  17990. */
  17991. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17992. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17993. return this;
  17994. };
  17995. /**
  17996. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17997. * Supports definition of mesh facing forward or backward.
  17998. * @param {number} flipBack
  17999. * @param {number} twirlClockwise
  18000. * @param {number} tiltRight
  18001. *
  18002. * Returns a new Vector3.
  18003. */
  18004. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18005. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18006. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18007. };
  18008. /**
  18009. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18010. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18011. */
  18012. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18013. if (includeDescendants === void 0) { includeDescendants = true; }
  18014. this.computeWorldMatrix(true);
  18015. var min;
  18016. var max;
  18017. var boundingInfo = this.getBoundingInfo();
  18018. if (!this.subMeshes) {
  18019. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18020. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18021. }
  18022. else {
  18023. min = boundingInfo.boundingBox.minimumWorld;
  18024. max = boundingInfo.boundingBox.maximumWorld;
  18025. }
  18026. if (includeDescendants) {
  18027. var descendants = this.getDescendants(false);
  18028. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18029. var descendant = descendants_1[_i];
  18030. var childMesh = descendant;
  18031. childMesh.computeWorldMatrix(true);
  18032. //make sure we have the needed params to get mix and max
  18033. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18034. continue;
  18035. }
  18036. var childBoundingInfo = childMesh.getBoundingInfo();
  18037. var boundingBox = childBoundingInfo.boundingBox;
  18038. var minBox = boundingBox.minimumWorld;
  18039. var maxBox = boundingBox.maximumWorld;
  18040. BABYLON.Tools.CheckExtends(minBox, min, max);
  18041. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18042. }
  18043. }
  18044. return {
  18045. min: min,
  18046. max: max
  18047. };
  18048. };
  18049. /**
  18050. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18051. * Returns the AbstractMesh.
  18052. */
  18053. AbstractMesh.prototype._updateBoundingInfo = function () {
  18054. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18055. this._boundingInfo.update(this.worldMatrixFromCache);
  18056. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18057. return this;
  18058. };
  18059. /**
  18060. * Update a mesh's children BoundingInfo objects only.
  18061. * Returns the AbstractMesh.
  18062. */
  18063. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18064. if (!this.subMeshes) {
  18065. return this;
  18066. }
  18067. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18068. var subMesh = this.subMeshes[subIndex];
  18069. if (!subMesh.IsGlobal) {
  18070. subMesh.updateBoundingInfo(matrix);
  18071. }
  18072. }
  18073. return this;
  18074. };
  18075. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18076. // Bounding info
  18077. this._updateBoundingInfo();
  18078. };
  18079. /**
  18080. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18081. * A mesh is in the frustum if its bounding box intersects the frustum.
  18082. * Boolean returned.
  18083. */
  18084. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18085. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18086. };
  18087. /**
  18088. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18089. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18090. * Boolean returned.
  18091. */
  18092. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18093. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18094. ;
  18095. };
  18096. /**
  18097. * True if the mesh intersects another mesh or a SolidParticle object.
  18098. * 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)
  18099. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18100. * Returns a boolean.
  18101. */
  18102. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18103. if (precise === void 0) { precise = false; }
  18104. if (!this._boundingInfo || !mesh._boundingInfo) {
  18105. return false;
  18106. }
  18107. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18108. return true;
  18109. }
  18110. if (includeDescendants) {
  18111. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18112. var child = _a[_i];
  18113. if (child.intersectsMesh(mesh, precise, true)) {
  18114. return true;
  18115. }
  18116. }
  18117. }
  18118. return false;
  18119. };
  18120. /**
  18121. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18122. * Returns a boolean.
  18123. */
  18124. AbstractMesh.prototype.intersectsPoint = function (point) {
  18125. if (!this._boundingInfo) {
  18126. return false;
  18127. }
  18128. return this._boundingInfo.intersectsPoint(point);
  18129. };
  18130. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18131. return this.physicsImpostor;
  18132. };
  18133. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18134. if (camera === void 0) { camera = null; }
  18135. if (!camera) {
  18136. camera = this.getScene().activeCamera;
  18137. }
  18138. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18139. };
  18140. /**
  18141. * Returns the distance from the mesh to the active camera.
  18142. * Returns a float.
  18143. */
  18144. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18145. if (camera === void 0) { camera = null; }
  18146. if (!camera) {
  18147. camera = this.getScene().activeCamera;
  18148. }
  18149. return this.absolutePosition.subtract(camera.position).length();
  18150. };
  18151. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18152. if (!this.physicsImpostor) {
  18153. return this;
  18154. }
  18155. this.physicsImpostor.applyImpulse(force, contactPoint);
  18156. return this;
  18157. };
  18158. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18159. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18160. return this;
  18161. }
  18162. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18163. mainPivot: pivot1,
  18164. connectedPivot: pivot2,
  18165. nativeParams: options
  18166. });
  18167. return this;
  18168. };
  18169. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18170. // Collisions
  18171. /**
  18172. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18173. * Default `false`.
  18174. */
  18175. get: function () {
  18176. return this._checkCollisions;
  18177. },
  18178. set: function (collisionEnabled) {
  18179. this._checkCollisions = collisionEnabled;
  18180. if (this.getScene().workerCollisions) {
  18181. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18182. }
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18188. /**
  18189. * Gets Collider object used to compute collisions (not physics)
  18190. */
  18191. get: function () {
  18192. return this._collider;
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18198. var globalPosition = this.getAbsolutePosition();
  18199. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18200. if (!this._collider) {
  18201. this._collider = new BABYLON.Collider();
  18202. }
  18203. this._collider._radius = this.ellipsoid;
  18204. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18205. return this;
  18206. };
  18207. // Submeshes octree
  18208. /**
  18209. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18210. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18211. * Returns an Octree of submeshes.
  18212. */
  18213. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18214. if (maxCapacity === void 0) { maxCapacity = 64; }
  18215. if (maxDepth === void 0) { maxDepth = 2; }
  18216. if (!this._submeshesOctree) {
  18217. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18218. }
  18219. this.computeWorldMatrix(true);
  18220. var boundingInfo = this.getBoundingInfo();
  18221. // Update octree
  18222. var bbox = boundingInfo.boundingBox;
  18223. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18224. return this._submeshesOctree;
  18225. };
  18226. // Collisions
  18227. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18228. this._generatePointsArray();
  18229. if (!this._positions) {
  18230. return this;
  18231. }
  18232. // Transformation
  18233. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18234. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18235. subMesh._lastColliderWorldVertices = [];
  18236. subMesh._trianglePlanes = [];
  18237. var start = subMesh.verticesStart;
  18238. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18239. for (var i = start; i < end; i++) {
  18240. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18241. }
  18242. }
  18243. // Collide
  18244. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18245. if (collider.collisionFound) {
  18246. collider.collidedMesh = this;
  18247. }
  18248. return this;
  18249. };
  18250. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18251. var subMeshes;
  18252. var len;
  18253. // Octrees
  18254. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18255. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18256. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18257. len = intersections.length;
  18258. subMeshes = intersections.data;
  18259. }
  18260. else {
  18261. subMeshes = this.subMeshes;
  18262. len = subMeshes.length;
  18263. }
  18264. for (var index = 0; index < len; index++) {
  18265. var subMesh = subMeshes[index];
  18266. // Bounding test
  18267. if (len > 1 && !subMesh._checkCollision(collider))
  18268. continue;
  18269. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18270. }
  18271. return this;
  18272. };
  18273. AbstractMesh.prototype._checkCollision = function (collider) {
  18274. // Bounding box test
  18275. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18276. return this;
  18277. // Transformation matrix
  18278. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18279. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18280. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18281. return this;
  18282. };
  18283. // Picking
  18284. AbstractMesh.prototype._generatePointsArray = function () {
  18285. return false;
  18286. };
  18287. /**
  18288. * Checks if the passed Ray intersects with the mesh.
  18289. * Returns an object PickingInfo.
  18290. */
  18291. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18292. var pickingInfo = new BABYLON.PickingInfo();
  18293. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18294. return pickingInfo;
  18295. }
  18296. if (!this._generatePointsArray()) {
  18297. return pickingInfo;
  18298. }
  18299. var intersectInfo = null;
  18300. // Octrees
  18301. var subMeshes;
  18302. var len;
  18303. if (this._submeshesOctree && this.useOctreeForPicking) {
  18304. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18305. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18306. len = intersections.length;
  18307. subMeshes = intersections.data;
  18308. }
  18309. else {
  18310. subMeshes = this.subMeshes;
  18311. len = subMeshes.length;
  18312. }
  18313. for (var index = 0; index < len; index++) {
  18314. var subMesh = subMeshes[index];
  18315. // Bounding test
  18316. if (len > 1 && !subMesh.canIntersects(ray))
  18317. continue;
  18318. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18319. if (currentIntersectInfo) {
  18320. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18321. intersectInfo = currentIntersectInfo;
  18322. intersectInfo.subMeshId = index;
  18323. if (fastCheck) {
  18324. break;
  18325. }
  18326. }
  18327. }
  18328. }
  18329. if (intersectInfo) {
  18330. // Get picked point
  18331. var world = this.getWorldMatrix();
  18332. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18333. var direction = ray.direction.clone();
  18334. direction = direction.scale(intersectInfo.distance);
  18335. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18336. var pickedPoint = worldOrigin.add(worldDirection);
  18337. // Return result
  18338. pickingInfo.hit = true;
  18339. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18340. pickingInfo.pickedPoint = pickedPoint;
  18341. pickingInfo.pickedMesh = this;
  18342. pickingInfo.bu = intersectInfo.bu || 0;
  18343. pickingInfo.bv = intersectInfo.bv || 0;
  18344. pickingInfo.faceId = intersectInfo.faceId;
  18345. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18346. return pickingInfo;
  18347. }
  18348. return pickingInfo;
  18349. };
  18350. /**
  18351. * Clones the mesh, used by the class Mesh.
  18352. * Just returns `null` for an AbstractMesh.
  18353. */
  18354. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18355. return null;
  18356. };
  18357. /**
  18358. * Disposes all the mesh submeshes.
  18359. * Returns the AbstractMesh.
  18360. */
  18361. AbstractMesh.prototype.releaseSubMeshes = function () {
  18362. if (this.subMeshes) {
  18363. while (this.subMeshes.length) {
  18364. this.subMeshes[0].dispose();
  18365. }
  18366. }
  18367. else {
  18368. this.subMeshes = new Array();
  18369. }
  18370. return this;
  18371. };
  18372. /**
  18373. * Disposes the AbstractMesh.
  18374. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18375. * Returns nothing.
  18376. */
  18377. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18378. var _this = this;
  18379. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18380. var index;
  18381. // Action manager
  18382. if (this.actionManager !== undefined && this.actionManager !== null) {
  18383. this.actionManager.dispose();
  18384. this.actionManager = null;
  18385. }
  18386. // Skeleton
  18387. this.skeleton = null;
  18388. // Physics
  18389. if (this.physicsImpostor) {
  18390. this.physicsImpostor.dispose();
  18391. }
  18392. // Intersections in progress
  18393. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18394. var other = this._intersectionsInProgress[index];
  18395. var pos = other._intersectionsInProgress.indexOf(this);
  18396. other._intersectionsInProgress.splice(pos, 1);
  18397. }
  18398. this._intersectionsInProgress = [];
  18399. // Lights
  18400. var lights = this.getScene().lights;
  18401. lights.forEach(function (light) {
  18402. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18403. if (meshIndex !== -1) {
  18404. light.includedOnlyMeshes.splice(meshIndex, 1);
  18405. }
  18406. meshIndex = light.excludedMeshes.indexOf(_this);
  18407. if (meshIndex !== -1) {
  18408. light.excludedMeshes.splice(meshIndex, 1);
  18409. }
  18410. // Shadow generators
  18411. var generator = light.getShadowGenerator();
  18412. if (generator) {
  18413. var shadowMap = generator.getShadowMap();
  18414. if (shadowMap && shadowMap.renderList) {
  18415. meshIndex = shadowMap.renderList.indexOf(_this);
  18416. if (meshIndex !== -1) {
  18417. shadowMap.renderList.splice(meshIndex, 1);
  18418. }
  18419. }
  18420. }
  18421. });
  18422. // Edges
  18423. if (this._edgesRenderer) {
  18424. this._edgesRenderer.dispose();
  18425. this._edgesRenderer = null;
  18426. }
  18427. // SubMeshes
  18428. if (this.getClassName() !== "InstancedMesh") {
  18429. this.releaseSubMeshes();
  18430. }
  18431. // Octree
  18432. var sceneOctree = this.getScene().selectionOctree;
  18433. if (sceneOctree !== undefined && sceneOctree !== null) {
  18434. var index = sceneOctree.dynamicContent.indexOf(this);
  18435. if (index !== -1) {
  18436. sceneOctree.dynamicContent.splice(index, 1);
  18437. }
  18438. }
  18439. // Query
  18440. var engine = this.getScene().getEngine();
  18441. if (this._occlusionQuery) {
  18442. this._isOcclusionQueryInProgress = false;
  18443. engine.deleteQuery(this._occlusionQuery);
  18444. this._occlusionQuery = null;
  18445. }
  18446. // Engine
  18447. engine.wipeCaches();
  18448. // Remove from scene
  18449. this.getScene().removeMesh(this);
  18450. if (disposeMaterialAndTextures) {
  18451. if (this.material) {
  18452. this.material.dispose(false, true);
  18453. }
  18454. }
  18455. if (!doNotRecurse) {
  18456. // Particles
  18457. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18458. if (this.getScene().particleSystems[index].emitter === this) {
  18459. this.getScene().particleSystems[index].dispose();
  18460. index--;
  18461. }
  18462. }
  18463. }
  18464. // facet data
  18465. if (this._facetDataEnabled) {
  18466. this.disableFacetData();
  18467. }
  18468. this.onAfterWorldMatrixUpdateObservable.clear();
  18469. this.onCollideObservable.clear();
  18470. this.onCollisionPositionChangeObservable.clear();
  18471. _super.prototype.dispose.call(this, doNotRecurse);
  18472. };
  18473. /**
  18474. * Adds the passed mesh as a child to the current mesh.
  18475. * Returns the AbstractMesh.
  18476. */
  18477. AbstractMesh.prototype.addChild = function (mesh) {
  18478. mesh.setParent(this);
  18479. return this;
  18480. };
  18481. /**
  18482. * Removes the passed mesh from the current mesh children list.
  18483. * Returns the AbstractMesh.
  18484. */
  18485. AbstractMesh.prototype.removeChild = function (mesh) {
  18486. mesh.setParent(null);
  18487. return this;
  18488. };
  18489. // Facet data
  18490. /**
  18491. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18492. * Returns the AbstractMesh.
  18493. */
  18494. AbstractMesh.prototype._initFacetData = function () {
  18495. if (!this._facetNormals) {
  18496. this._facetNormals = new Array();
  18497. }
  18498. if (!this._facetPositions) {
  18499. this._facetPositions = new Array();
  18500. }
  18501. if (!this._facetPartitioning) {
  18502. this._facetPartitioning = new Array();
  18503. }
  18504. this._facetNb = (this.getIndices().length / 3) | 0;
  18505. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18506. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18507. for (var f = 0; f < this._facetNb; f++) {
  18508. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18509. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18510. }
  18511. this._facetDataEnabled = true;
  18512. return this;
  18513. };
  18514. /**
  18515. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18516. * This method can be called within the render loop.
  18517. * 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.
  18518. * Returns the AbstractMesh.
  18519. */
  18520. AbstractMesh.prototype.updateFacetData = function () {
  18521. if (!this._facetDataEnabled) {
  18522. this._initFacetData();
  18523. }
  18524. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18525. var indices = this.getIndices();
  18526. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18527. var bInfo = this.getBoundingInfo();
  18528. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18529. // init arrays, matrix and sort function on first call
  18530. this._facetDepthSortEnabled = true;
  18531. if (indices instanceof Uint16Array) {
  18532. this._depthSortedIndices = new Uint16Array(indices);
  18533. }
  18534. else if (indices instanceof Uint32Array) {
  18535. this._depthSortedIndices = new Uint32Array(indices);
  18536. }
  18537. else {
  18538. var needs32bits = false;
  18539. for (var i = 0; i < indices.length; i++) {
  18540. if (indices[i] > 65535) {
  18541. needs32bits = true;
  18542. break;
  18543. }
  18544. }
  18545. if (needs32bits) {
  18546. this._depthSortedIndices = new Uint32Array(indices);
  18547. }
  18548. else {
  18549. this._depthSortedIndices = new Uint16Array(indices);
  18550. }
  18551. }
  18552. this._facetDepthSortFunction = function (f1, f2) {
  18553. return (f2.sqDistance - f1.sqDistance);
  18554. };
  18555. if (!this._facetDepthSortFrom) {
  18556. var camera = this.getScene().activeCamera;
  18557. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18558. }
  18559. this._depthSortedFacets = [];
  18560. for (var f = 0; f < this._facetNb; f++) {
  18561. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18562. this._depthSortedFacets.push(depthSortedFacet);
  18563. }
  18564. this._invertedMatrix = BABYLON.Matrix.Identity();
  18565. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18566. }
  18567. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18568. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18569. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18570. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18571. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18572. this._subDiv.max = this._partitioningSubdivisions;
  18573. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18574. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18575. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18576. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18577. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18578. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18579. // set the parameters for ComputeNormals()
  18580. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18581. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18582. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18583. this._facetParameters.bInfo = bInfo;
  18584. this._facetParameters.bbSize = this._bbSize;
  18585. this._facetParameters.subDiv = this._subDiv;
  18586. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18587. this._facetParameters.depthSort = this._facetDepthSort;
  18588. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18589. this.computeWorldMatrix(true);
  18590. this._worldMatrix.invertToRef(this._invertedMatrix);
  18591. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18592. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18593. }
  18594. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18595. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18596. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18597. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18598. var l = (this._depthSortedIndices.length / 3) | 0;
  18599. for (var f = 0; f < l; f++) {
  18600. var sind = this._depthSortedFacets[f].ind;
  18601. this._depthSortedIndices[f * 3] = indices[sind];
  18602. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18603. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18604. }
  18605. this.updateIndices(this._depthSortedIndices);
  18606. }
  18607. return this;
  18608. };
  18609. /**
  18610. * Returns the facetLocalNormals array.
  18611. * The normals are expressed in the mesh local space.
  18612. */
  18613. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18614. if (!this._facetNormals) {
  18615. this.updateFacetData();
  18616. }
  18617. return this._facetNormals;
  18618. };
  18619. /**
  18620. * Returns the facetLocalPositions array.
  18621. * The facet positions are expressed in the mesh local space.
  18622. */
  18623. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18624. if (!this._facetPositions) {
  18625. this.updateFacetData();
  18626. }
  18627. return this._facetPositions;
  18628. };
  18629. /**
  18630. * Returns the facetLocalPartioning array.
  18631. */
  18632. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18633. if (!this._facetPartitioning) {
  18634. this.updateFacetData();
  18635. }
  18636. return this._facetPartitioning;
  18637. };
  18638. /**
  18639. * Returns the i-th facet position in the world system.
  18640. * This method allocates a new Vector3 per call.
  18641. */
  18642. AbstractMesh.prototype.getFacetPosition = function (i) {
  18643. var pos = BABYLON.Vector3.Zero();
  18644. this.getFacetPositionToRef(i, pos);
  18645. return pos;
  18646. };
  18647. /**
  18648. * Sets the reference Vector3 with the i-th facet position in the world system.
  18649. * Returns the AbstractMesh.
  18650. */
  18651. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18652. var localPos = (this.getFacetLocalPositions())[i];
  18653. var world = this.getWorldMatrix();
  18654. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18655. return this;
  18656. };
  18657. /**
  18658. * Returns the i-th facet normal in the world system.
  18659. * This method allocates a new Vector3 per call.
  18660. */
  18661. AbstractMesh.prototype.getFacetNormal = function (i) {
  18662. var norm = BABYLON.Vector3.Zero();
  18663. this.getFacetNormalToRef(i, norm);
  18664. return norm;
  18665. };
  18666. /**
  18667. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18668. * Returns the AbstractMesh.
  18669. */
  18670. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18671. var localNorm = (this.getFacetLocalNormals())[i];
  18672. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18673. return this;
  18674. };
  18675. /**
  18676. * 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).
  18677. */
  18678. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18679. var bInfo = this.getBoundingInfo();
  18680. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18681. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18682. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18683. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18684. return null;
  18685. }
  18686. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18687. };
  18688. /**
  18689. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18690. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18691. * 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.
  18692. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18693. * 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.
  18694. */
  18695. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18696. if (checkFace === void 0) { checkFace = false; }
  18697. if (facing === void 0) { facing = true; }
  18698. var world = this.getWorldMatrix();
  18699. var invMat = BABYLON.Tmp.Matrix[5];
  18700. world.invertToRef(invMat);
  18701. var invVect = BABYLON.Tmp.Vector3[8];
  18702. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18703. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18704. if (projected) {
  18705. // tranform the local computed projected vector to world coordinates
  18706. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18707. }
  18708. return closest;
  18709. };
  18710. /**
  18711. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18712. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18713. * 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.
  18714. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18715. * 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.
  18716. */
  18717. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18718. if (checkFace === void 0) { checkFace = false; }
  18719. if (facing === void 0) { facing = true; }
  18720. var closest = null;
  18721. var tmpx = 0.0;
  18722. var tmpy = 0.0;
  18723. var tmpz = 0.0;
  18724. var d = 0.0; // tmp dot facet normal * facet position
  18725. var t0 = 0.0;
  18726. var projx = 0.0;
  18727. var projy = 0.0;
  18728. var projz = 0.0;
  18729. // Get all the facets in the same partitioning block than (x, y, z)
  18730. var facetPositions = this.getFacetLocalPositions();
  18731. var facetNormals = this.getFacetLocalNormals();
  18732. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18733. if (!facetsInBlock) {
  18734. return null;
  18735. }
  18736. // Get the closest facet to (x, y, z)
  18737. var shortest = Number.MAX_VALUE; // init distance vars
  18738. var tmpDistance = shortest;
  18739. var fib; // current facet in the block
  18740. var norm; // current facet normal
  18741. var p0; // current facet barycenter position
  18742. // loop on all the facets in the current partitioning block
  18743. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18744. fib = facetsInBlock[idx];
  18745. norm = facetNormals[fib];
  18746. p0 = facetPositions[fib];
  18747. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18748. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18749. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18750. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18751. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18752. projx = x + norm.x * t0;
  18753. projy = y + norm.y * t0;
  18754. projz = z + norm.z * t0;
  18755. tmpx = projx - x;
  18756. tmpy = projy - y;
  18757. tmpz = projz - z;
  18758. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18759. if (tmpDistance < shortest) {
  18760. shortest = tmpDistance;
  18761. closest = fib;
  18762. if (projected) {
  18763. projected.x = projx;
  18764. projected.y = projy;
  18765. projected.z = projz;
  18766. }
  18767. }
  18768. }
  18769. }
  18770. return closest;
  18771. };
  18772. /**
  18773. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18774. */
  18775. AbstractMesh.prototype.getFacetDataParameters = function () {
  18776. return this._facetParameters;
  18777. };
  18778. /**
  18779. * Disables the feature FacetData and frees the related memory.
  18780. * Returns the AbstractMesh.
  18781. */
  18782. AbstractMesh.prototype.disableFacetData = function () {
  18783. if (this._facetDataEnabled) {
  18784. this._facetDataEnabled = false;
  18785. this._facetPositions = new Array();
  18786. this._facetNormals = new Array();
  18787. this._facetPartitioning = new Array();
  18788. this._facetParameters = null;
  18789. this._depthSortedIndices = new Uint32Array(0);
  18790. }
  18791. return this;
  18792. };
  18793. /**
  18794. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18795. * Returns the mesh.
  18796. */
  18797. AbstractMesh.prototype.updateIndices = function (indices) {
  18798. return this;
  18799. };
  18800. /**
  18801. * The mesh Geometry. Actually used by the Mesh object.
  18802. * Returns a blank geometry object.
  18803. */
  18804. /**
  18805. * Creates new normals data for the mesh.
  18806. * @param updatable.
  18807. */
  18808. AbstractMesh.prototype.createNormals = function (updatable) {
  18809. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18810. var indices = this.getIndices();
  18811. var normals;
  18812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18813. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18814. }
  18815. else {
  18816. normals = [];
  18817. }
  18818. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18819. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18820. };
  18821. /**
  18822. * Align the mesh with a normal.
  18823. * Returns the mesh.
  18824. */
  18825. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18826. if (!upDirection) {
  18827. upDirection = BABYLON.Axis.Y;
  18828. }
  18829. var axisX = BABYLON.Tmp.Vector3[0];
  18830. var axisZ = BABYLON.Tmp.Vector3[1];
  18831. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18832. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18833. if (this.rotationQuaternion) {
  18834. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18835. }
  18836. else {
  18837. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18838. }
  18839. return this;
  18840. };
  18841. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18842. var engine = this.getEngine();
  18843. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18844. this._isOccluded = false;
  18845. return;
  18846. }
  18847. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18848. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18849. if (isOcclusionQueryAvailable) {
  18850. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18851. this._isOcclusionQueryInProgress = false;
  18852. this._occlusionInternalRetryCounter = 0;
  18853. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18854. }
  18855. else {
  18856. this._occlusionInternalRetryCounter++;
  18857. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18858. this._isOcclusionQueryInProgress = false;
  18859. this._occlusionInternalRetryCounter = 0;
  18860. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18861. // if strict continue the last state of the object.
  18862. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18863. }
  18864. else {
  18865. return;
  18866. }
  18867. }
  18868. }
  18869. var scene = this.getScene();
  18870. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18871. if (!this._occlusionQuery) {
  18872. this._occlusionQuery = engine.createQuery();
  18873. }
  18874. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18875. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18876. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18877. this._isOcclusionQueryInProgress = true;
  18878. };
  18879. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18880. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18881. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18882. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18883. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18884. return AbstractMesh;
  18885. }(BABYLON.TransformNode));
  18886. BABYLON.AbstractMesh = AbstractMesh;
  18887. })(BABYLON || (BABYLON = {}));
  18888. //# sourceMappingURL=babylon.abstractMesh.js.map
  18889. var BABYLON;
  18890. (function (BABYLON) {
  18891. /**
  18892. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18893. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18894. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  18895. */
  18896. var Light = /** @class */ (function (_super) {
  18897. __extends(Light, _super);
  18898. /**
  18899. * Creates a Light object in the scene.
  18900. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18901. * @param name The firendly name of the light
  18902. * @param scene The scene the light belongs too
  18903. */
  18904. function Light(name, scene) {
  18905. var _this = _super.call(this, name, scene) || this;
  18906. /**
  18907. * Diffuse gives the basic color to an object.
  18908. */
  18909. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18910. /**
  18911. * Specular produces a highlight color on an object.
  18912. * Note: This is note affecting PBR materials.
  18913. */
  18914. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18915. /**
  18916. * Strength of the light.
  18917. * Note: By default it is define in the framework own unit.
  18918. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18919. */
  18920. _this.intensity = 1.0;
  18921. /**
  18922. * Defines how far from the source the light is impacting in scene units.
  18923. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18924. */
  18925. _this.range = Number.MAX_VALUE;
  18926. /**
  18927. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18928. * of light.
  18929. */
  18930. _this._photometricScale = 1.0;
  18931. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18932. _this._radius = 0.00001;
  18933. /**
  18934. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18935. * exceeding the number allowed of the materials.
  18936. */
  18937. _this.renderPriority = 0;
  18938. /**
  18939. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18940. * the current shadow generator.
  18941. */
  18942. _this.shadowEnabled = true;
  18943. _this._excludeWithLayerMask = 0;
  18944. _this._includeOnlyWithLayerMask = 0;
  18945. _this._lightmapMode = 0;
  18946. /**
  18947. * @ignore Internal use only.
  18948. */
  18949. _this._excludedMeshesIds = new Array();
  18950. /**
  18951. * @ignore Internal use only.
  18952. */
  18953. _this._includedOnlyMeshesIds = new Array();
  18954. _this.getScene().addLight(_this);
  18955. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18956. _this._buildUniformLayout();
  18957. _this.includedOnlyMeshes = new Array();
  18958. _this.excludedMeshes = new Array();
  18959. _this._resyncMeshes();
  18960. return _this;
  18961. }
  18962. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18963. /**
  18964. * If every light affecting the material is in this lightmapMode,
  18965. * material.lightmapTexture adds or multiplies
  18966. * (depends on material.useLightmapAsShadowmap)
  18967. * after every other light calculations.
  18968. */
  18969. get: function () {
  18970. return Light._LIGHTMAP_DEFAULT;
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18976. /**
  18977. * material.lightmapTexture as only diffuse lighting from this light
  18978. * adds only specular lighting from this light
  18979. * adds dynamic shadows
  18980. */
  18981. get: function () {
  18982. return Light._LIGHTMAP_SPECULAR;
  18983. },
  18984. enumerable: true,
  18985. configurable: true
  18986. });
  18987. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18988. /**
  18989. * material.lightmapTexture as only lighting
  18990. * no light calculation from this light
  18991. * only adds dynamic shadows from this light
  18992. */
  18993. get: function () {
  18994. return Light._LIGHTMAP_SHADOWSONLY;
  18995. },
  18996. enumerable: true,
  18997. configurable: true
  18998. });
  18999. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19000. /**
  19001. * Each light type uses the default quantity according to its type:
  19002. * point/spot lights use luminous intensity
  19003. * directional lights use illuminance
  19004. */
  19005. get: function () {
  19006. return Light._INTENSITYMODE_AUTOMATIC;
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19012. /**
  19013. * lumen (lm)
  19014. */
  19015. get: function () {
  19016. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19017. },
  19018. enumerable: true,
  19019. configurable: true
  19020. });
  19021. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19022. /**
  19023. * candela (lm/sr)
  19024. */
  19025. get: function () {
  19026. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19032. /**
  19033. * lux (lm/m^2)
  19034. */
  19035. get: function () {
  19036. return Light._INTENSITYMODE_ILLUMINANCE;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19042. /**
  19043. * nit (cd/m^2)
  19044. */
  19045. get: function () {
  19046. return Light._INTENSITYMODE_LUMINANCE;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19052. /**
  19053. * Light type const id of the point light.
  19054. */
  19055. get: function () {
  19056. return Light._LIGHTTYPEID_POINTLIGHT;
  19057. },
  19058. enumerable: true,
  19059. configurable: true
  19060. });
  19061. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19062. /**
  19063. * Light type const id of the directional light.
  19064. */
  19065. get: function () {
  19066. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19072. /**
  19073. * Light type const id of the spot light.
  19074. */
  19075. get: function () {
  19076. return Light._LIGHTTYPEID_SPOTLIGHT;
  19077. },
  19078. enumerable: true,
  19079. configurable: true
  19080. });
  19081. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19082. /**
  19083. * Light type const id of the hemispheric light.
  19084. */
  19085. get: function () {
  19086. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Light.prototype, "intensityMode", {
  19092. /**
  19093. * Gets the photometric scale used to interpret the intensity.
  19094. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19095. */
  19096. get: function () {
  19097. return this._intensityMode;
  19098. },
  19099. /**
  19100. * Sets the photometric scale used to interpret the intensity.
  19101. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19102. */
  19103. set: function (value) {
  19104. this._intensityMode = value;
  19105. this._computePhotometricScale();
  19106. },
  19107. enumerable: true,
  19108. configurable: true
  19109. });
  19110. ;
  19111. ;
  19112. Object.defineProperty(Light.prototype, "radius", {
  19113. /**
  19114. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19115. */
  19116. get: function () {
  19117. return this._radius;
  19118. },
  19119. /**
  19120. * sets the light radius used by PBR Materials to simulate soft area lights.
  19121. */
  19122. set: function (value) {
  19123. this._radius = value;
  19124. this._computePhotometricScale();
  19125. },
  19126. enumerable: true,
  19127. configurable: true
  19128. });
  19129. ;
  19130. ;
  19131. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19132. /**
  19133. * Gets the only meshes impacted by this light.
  19134. */
  19135. get: function () {
  19136. return this._includedOnlyMeshes;
  19137. },
  19138. /**
  19139. * Sets the only meshes impacted by this light.
  19140. */
  19141. set: function (value) {
  19142. this._includedOnlyMeshes = value;
  19143. this._hookArrayForIncludedOnly(value);
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19149. /**
  19150. * Gets the meshes not impacted by this light.
  19151. */
  19152. get: function () {
  19153. return this._excludedMeshes;
  19154. },
  19155. /**
  19156. * Sets the meshes not impacted by this light.
  19157. */
  19158. set: function (value) {
  19159. this._excludedMeshes = value;
  19160. this._hookArrayForExcluded(value);
  19161. },
  19162. enumerable: true,
  19163. configurable: true
  19164. });
  19165. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19166. /**
  19167. * Gets the layer id use to find what meshes are not impacted by the light.
  19168. * Inactive if 0
  19169. */
  19170. get: function () {
  19171. return this._excludeWithLayerMask;
  19172. },
  19173. /**
  19174. * Sets the layer id use to find what meshes are not impacted by the light.
  19175. * Inactive if 0
  19176. */
  19177. set: function (value) {
  19178. this._excludeWithLayerMask = value;
  19179. this._resyncMeshes();
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19185. /**
  19186. * Gets the layer id use to find what meshes are impacted by the light.
  19187. * Inactive if 0
  19188. */
  19189. get: function () {
  19190. return this._includeOnlyWithLayerMask;
  19191. },
  19192. /**
  19193. * Sets the layer id use to find what meshes are impacted by the light.
  19194. * Inactive if 0
  19195. */
  19196. set: function (value) {
  19197. this._includeOnlyWithLayerMask = value;
  19198. this._resyncMeshes();
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. Object.defineProperty(Light.prototype, "lightmapMode", {
  19204. /**
  19205. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19206. */
  19207. get: function () {
  19208. return this._lightmapMode;
  19209. },
  19210. /**
  19211. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19212. */
  19213. set: function (value) {
  19214. if (this._lightmapMode === value) {
  19215. return;
  19216. }
  19217. this._lightmapMode = value;
  19218. this._markMeshesAsLightDirty();
  19219. },
  19220. enumerable: true,
  19221. configurable: true
  19222. });
  19223. /**
  19224. * Returns the string "Light".
  19225. * @returns the class name
  19226. */
  19227. Light.prototype.getClassName = function () {
  19228. return "Light";
  19229. };
  19230. /**
  19231. * Converts the light information to a readable string for debug purpose.
  19232. * @param fullDetails Supports for multiple levels of logging within scene loading
  19233. * @returns the human readable light info
  19234. */
  19235. Light.prototype.toString = function (fullDetails) {
  19236. var ret = "Name: " + this.name;
  19237. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19238. if (this.animations) {
  19239. for (var i = 0; i < this.animations.length; i++) {
  19240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19241. }
  19242. }
  19243. if (fullDetails) {
  19244. }
  19245. return ret;
  19246. };
  19247. /**
  19248. * Set the enabled state of this node.
  19249. * @param value - the new enabled state
  19250. * @see isEnabled
  19251. */
  19252. Light.prototype.setEnabled = function (value) {
  19253. _super.prototype.setEnabled.call(this, value);
  19254. this._resyncMeshes();
  19255. };
  19256. /**
  19257. * Returns the Light associated shadow generator if any.
  19258. * @return the associated shadow generator.
  19259. */
  19260. Light.prototype.getShadowGenerator = function () {
  19261. return this._shadowGenerator;
  19262. };
  19263. /**
  19264. * Returns a Vector3, the absolute light position in the World.
  19265. * @returns the world space position of the light
  19266. */
  19267. Light.prototype.getAbsolutePosition = function () {
  19268. return BABYLON.Vector3.Zero();
  19269. };
  19270. /**
  19271. * Specifies if the light will affect the passed mesh.
  19272. * @param mesh The mesh to test against the light
  19273. * @return true the mesh is affected otherwise, false.
  19274. */
  19275. Light.prototype.canAffectMesh = function (mesh) {
  19276. if (!mesh) {
  19277. return true;
  19278. }
  19279. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19280. return false;
  19281. }
  19282. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19283. return false;
  19284. }
  19285. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19286. return false;
  19287. }
  19288. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19289. return false;
  19290. }
  19291. return true;
  19292. };
  19293. /**
  19294. * Computes and Returns the light World matrix.
  19295. * @returns the world matrix
  19296. */
  19297. Light.prototype.getWorldMatrix = function () {
  19298. this._currentRenderId = this.getScene().getRenderId();
  19299. var worldMatrix = this._getWorldMatrix();
  19300. if (this.parent && this.parent.getWorldMatrix) {
  19301. if (!this._parentedWorldMatrix) {
  19302. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19303. }
  19304. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19305. this._markSyncedWithParent();
  19306. return this._parentedWorldMatrix;
  19307. }
  19308. return worldMatrix;
  19309. };
  19310. /**
  19311. * Sort function to order lights for rendering.
  19312. * @param a First Light object to compare to second.
  19313. * @param b Second Light object to compare first.
  19314. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19315. */
  19316. Light.CompareLightsPriority = function (a, b) {
  19317. //shadow-casting lights have priority over non-shadow-casting lights
  19318. //the renderPrioirty is a secondary sort criterion
  19319. if (a.shadowEnabled !== b.shadowEnabled) {
  19320. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19321. }
  19322. return b.renderPriority - a.renderPriority;
  19323. };
  19324. /**
  19325. * Disposes the light.
  19326. */
  19327. Light.prototype.dispose = function () {
  19328. if (this._shadowGenerator) {
  19329. this._shadowGenerator.dispose();
  19330. this._shadowGenerator = null;
  19331. }
  19332. // Animations
  19333. this.getScene().stopAnimation(this);
  19334. // Remove from meshes
  19335. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19336. var mesh = _a[_i];
  19337. mesh._removeLightSource(this);
  19338. }
  19339. this._uniformBuffer.dispose();
  19340. // Remove from scene
  19341. this.getScene().removeLight(this);
  19342. _super.prototype.dispose.call(this);
  19343. };
  19344. /**
  19345. * Returns the light type ID (integer).
  19346. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19347. */
  19348. Light.prototype.getTypeID = function () {
  19349. return 0;
  19350. };
  19351. /**
  19352. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19353. * @returns the scaled intensity in intensity mode unit
  19354. */
  19355. Light.prototype.getScaledIntensity = function () {
  19356. return this._photometricScale * this.intensity;
  19357. };
  19358. /**
  19359. * Returns a new Light object, named "name", from the current one.
  19360. * @param name The name of the cloned light
  19361. * @returns the new created light
  19362. */
  19363. Light.prototype.clone = function (name) {
  19364. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19365. if (!constructor) {
  19366. return null;
  19367. }
  19368. return BABYLON.SerializationHelper.Clone(constructor, this);
  19369. };
  19370. /**
  19371. * Serializes the current light into a Serialization object.
  19372. * @returns the serialized object.
  19373. */
  19374. Light.prototype.serialize = function () {
  19375. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19376. // Type
  19377. serializationObject.type = this.getTypeID();
  19378. // Parent
  19379. if (this.parent) {
  19380. serializationObject.parentId = this.parent.id;
  19381. }
  19382. // Inclusion / exclusions
  19383. if (this.excludedMeshes.length > 0) {
  19384. serializationObject.excludedMeshesIds = [];
  19385. this.excludedMeshes.forEach(function (mesh) {
  19386. serializationObject.excludedMeshesIds.push(mesh.id);
  19387. });
  19388. }
  19389. if (this.includedOnlyMeshes.length > 0) {
  19390. serializationObject.includedOnlyMeshesIds = [];
  19391. this.includedOnlyMeshes.forEach(function (mesh) {
  19392. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19393. });
  19394. }
  19395. // Animations
  19396. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19397. serializationObject.ranges = this.serializeAnimationRanges();
  19398. return serializationObject;
  19399. };
  19400. /**
  19401. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19402. * This new light is named "name" and added to the passed scene.
  19403. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19404. * @param name The friendly name of the light
  19405. * @param scene The scene the new light will belong to
  19406. * @returns the constructor function
  19407. */
  19408. Light.GetConstructorFromName = function (type, name, scene) {
  19409. switch (type) {
  19410. case 0:
  19411. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19412. case 1:
  19413. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19414. case 2:
  19415. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19416. case 3:
  19417. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19418. }
  19419. return null;
  19420. };
  19421. /**
  19422. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19423. * @param parsedLight The JSON representation of the light
  19424. * @param scene The scene to create the parsed light in
  19425. * @returns the created light after parsing
  19426. */
  19427. Light.Parse = function (parsedLight, scene) {
  19428. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19429. if (!constructor) {
  19430. return null;
  19431. }
  19432. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19433. // Inclusion / exclusions
  19434. if (parsedLight.excludedMeshesIds) {
  19435. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19436. }
  19437. if (parsedLight.includedOnlyMeshesIds) {
  19438. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19439. }
  19440. // Parent
  19441. if (parsedLight.parentId) {
  19442. light._waitingParentId = parsedLight.parentId;
  19443. }
  19444. // Animations
  19445. if (parsedLight.animations) {
  19446. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19447. var parsedAnimation = parsedLight.animations[animationIndex];
  19448. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19449. }
  19450. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19451. }
  19452. if (parsedLight.autoAnimate) {
  19453. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19454. }
  19455. return light;
  19456. };
  19457. Light.prototype._hookArrayForExcluded = function (array) {
  19458. var _this = this;
  19459. var oldPush = array.push;
  19460. array.push = function () {
  19461. var items = [];
  19462. for (var _i = 0; _i < arguments.length; _i++) {
  19463. items[_i] = arguments[_i];
  19464. }
  19465. var result = oldPush.apply(array, items);
  19466. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19467. var item = items_1[_a];
  19468. item._resyncLighSource(_this);
  19469. }
  19470. return result;
  19471. };
  19472. var oldSplice = array.splice;
  19473. array.splice = function (index, deleteCount) {
  19474. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19475. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19476. var item = deleted_1[_i];
  19477. item._resyncLighSource(_this);
  19478. }
  19479. return deleted;
  19480. };
  19481. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19482. var item = array_1[_i];
  19483. item._resyncLighSource(this);
  19484. }
  19485. };
  19486. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19487. var _this = this;
  19488. var oldPush = array.push;
  19489. array.push = function () {
  19490. var items = [];
  19491. for (var _i = 0; _i < arguments.length; _i++) {
  19492. items[_i] = arguments[_i];
  19493. }
  19494. var result = oldPush.apply(array, items);
  19495. _this._resyncMeshes();
  19496. return result;
  19497. };
  19498. var oldSplice = array.splice;
  19499. array.splice = function (index, deleteCount) {
  19500. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19501. _this._resyncMeshes();
  19502. return deleted;
  19503. };
  19504. this._resyncMeshes();
  19505. };
  19506. Light.prototype._resyncMeshes = function () {
  19507. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19508. var mesh = _a[_i];
  19509. mesh._resyncLighSource(this);
  19510. }
  19511. };
  19512. /**
  19513. * Forces the meshes to update their light related information in their rendering used effects
  19514. * @ignore Internal Use Only
  19515. */
  19516. Light.prototype._markMeshesAsLightDirty = function () {
  19517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19518. var mesh = _a[_i];
  19519. if (mesh._lightSources.indexOf(this) !== -1) {
  19520. mesh._markSubMeshesAsLightDirty();
  19521. }
  19522. }
  19523. };
  19524. /**
  19525. * Recomputes the cached photometric scale if needed.
  19526. */
  19527. Light.prototype._computePhotometricScale = function () {
  19528. this._photometricScale = this._getPhotometricScale();
  19529. this.getScene().resetCachedMaterial();
  19530. };
  19531. /**
  19532. * Returns the Photometric Scale according to the light type and intensity mode.
  19533. */
  19534. Light.prototype._getPhotometricScale = function () {
  19535. var photometricScale = 0.0;
  19536. var lightTypeID = this.getTypeID();
  19537. //get photometric mode
  19538. var photometricMode = this.intensityMode;
  19539. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19540. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19541. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19542. }
  19543. else {
  19544. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19545. }
  19546. }
  19547. //compute photometric scale
  19548. switch (lightTypeID) {
  19549. case Light.LIGHTTYPEID_POINTLIGHT:
  19550. case Light.LIGHTTYPEID_SPOTLIGHT:
  19551. switch (photometricMode) {
  19552. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19553. photometricScale = 1.0 / (4.0 * Math.PI);
  19554. break;
  19555. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19556. photometricScale = 1.0;
  19557. break;
  19558. case Light.INTENSITYMODE_LUMINANCE:
  19559. photometricScale = this.radius * this.radius;
  19560. break;
  19561. }
  19562. break;
  19563. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19564. switch (photometricMode) {
  19565. case Light.INTENSITYMODE_ILLUMINANCE:
  19566. photometricScale = 1.0;
  19567. break;
  19568. case Light.INTENSITYMODE_LUMINANCE:
  19569. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19570. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19571. var apexAngleRadians = this.radius;
  19572. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19573. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19574. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19575. photometricScale = solidAngle;
  19576. break;
  19577. }
  19578. break;
  19579. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19580. // No fall off in hemisperic light.
  19581. photometricScale = 1.0;
  19582. break;
  19583. }
  19584. return photometricScale;
  19585. };
  19586. /**
  19587. * Reorder the light in the scene according to their defined priority.
  19588. * @ignore Internal Use Only
  19589. */
  19590. Light.prototype._reorderLightsInScene = function () {
  19591. var scene = this.getScene();
  19592. if (this._renderPriority != 0) {
  19593. scene.requireLightSorting = true;
  19594. }
  19595. this.getScene().sortLightsByPriority();
  19596. };
  19597. //lightmapMode Consts
  19598. Light._LIGHTMAP_DEFAULT = 0;
  19599. Light._LIGHTMAP_SPECULAR = 1;
  19600. Light._LIGHTMAP_SHADOWSONLY = 2;
  19601. // Intensity Mode Consts
  19602. Light._INTENSITYMODE_AUTOMATIC = 0;
  19603. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19604. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19605. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19606. Light._INTENSITYMODE_LUMINANCE = 4;
  19607. // Light types ids const.
  19608. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19609. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19610. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19611. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19612. __decorate([
  19613. BABYLON.serializeAsColor3()
  19614. ], Light.prototype, "diffuse", void 0);
  19615. __decorate([
  19616. BABYLON.serializeAsColor3()
  19617. ], Light.prototype, "specular", void 0);
  19618. __decorate([
  19619. BABYLON.serialize()
  19620. ], Light.prototype, "intensity", void 0);
  19621. __decorate([
  19622. BABYLON.serialize()
  19623. ], Light.prototype, "range", void 0);
  19624. __decorate([
  19625. BABYLON.serialize()
  19626. ], Light.prototype, "intensityMode", null);
  19627. __decorate([
  19628. BABYLON.serialize()
  19629. ], Light.prototype, "radius", null);
  19630. __decorate([
  19631. BABYLON.serialize()
  19632. ], Light.prototype, "_renderPriority", void 0);
  19633. __decorate([
  19634. BABYLON.expandToProperty("_reorderLightsInScene")
  19635. ], Light.prototype, "renderPriority", void 0);
  19636. __decorate([
  19637. BABYLON.serialize()
  19638. ], Light.prototype, "shadowEnabled", void 0);
  19639. __decorate([
  19640. BABYLON.serialize("excludeWithLayerMask")
  19641. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19642. __decorate([
  19643. BABYLON.serialize("includeOnlyWithLayerMask")
  19644. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19645. __decorate([
  19646. BABYLON.serialize("lightmapMode")
  19647. ], Light.prototype, "_lightmapMode", void 0);
  19648. return Light;
  19649. }(BABYLON.Node));
  19650. BABYLON.Light = Light;
  19651. })(BABYLON || (BABYLON = {}));
  19652. //# sourceMappingURL=babylon.light.js.map
  19653. var BABYLON;
  19654. (function (BABYLON) {
  19655. var Camera = /** @class */ (function (_super) {
  19656. __extends(Camera, _super);
  19657. function Camera(name, position, scene) {
  19658. var _this = _super.call(this, name, scene) || this;
  19659. /**
  19660. * The vector the camera should consider as up.
  19661. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19662. */
  19663. _this.upVector = BABYLON.Vector3.Up();
  19664. _this.orthoLeft = null;
  19665. _this.orthoRight = null;
  19666. _this.orthoBottom = null;
  19667. _this.orthoTop = null;
  19668. /**
  19669. * FOV is set in Radians. (default is 0.8)
  19670. */
  19671. _this.fov = 0.8;
  19672. _this.minZ = 1;
  19673. _this.maxZ = 10000.0;
  19674. _this.inertia = 0.9;
  19675. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19676. _this.isIntermediate = false;
  19677. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19678. /**
  19679. * Restricts the camera to viewing objects with the same layerMask.
  19680. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19681. */
  19682. _this.layerMask = 0x0FFFFFFF;
  19683. /**
  19684. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19685. */
  19686. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19687. // Camera rig members
  19688. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19689. _this._rigCameras = new Array();
  19690. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19691. _this._skipRendering = false;
  19692. _this.customRenderTargets = new Array();
  19693. // Observables
  19694. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19695. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19696. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19697. _this.onRestoreStateObservable = new BABYLON.Observable();
  19698. // Cache
  19699. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19700. _this._projectionMatrix = new BABYLON.Matrix();
  19701. _this._doNotComputeProjectionMatrix = false;
  19702. _this._postProcesses = new Array();
  19703. _this._transformMatrix = BABYLON.Matrix.Zero();
  19704. _this._activeMeshes = new BABYLON.SmartArray(256);
  19705. _this._globalPosition = BABYLON.Vector3.Zero();
  19706. _this._refreshFrustumPlanes = true;
  19707. _this.getScene().addCamera(_this);
  19708. if (!_this.getScene().activeCamera) {
  19709. _this.getScene().activeCamera = _this;
  19710. }
  19711. _this.position = position;
  19712. return _this;
  19713. }
  19714. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19715. get: function () {
  19716. return Camera._PERSPECTIVE_CAMERA;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19722. get: function () {
  19723. return Camera._ORTHOGRAPHIC_CAMERA;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19729. /**
  19730. * This is the default FOV mode for perspective cameras.
  19731. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19732. *
  19733. */
  19734. get: function () {
  19735. return Camera._FOVMODE_VERTICAL_FIXED;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19741. /**
  19742. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19743. *
  19744. */
  19745. get: function () {
  19746. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19752. get: function () {
  19753. return Camera._RIG_MODE_NONE;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19759. get: function () {
  19760. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19766. get: function () {
  19767. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19773. get: function () {
  19774. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19780. get: function () {
  19781. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19787. get: function () {
  19788. return Camera._RIG_MODE_VR;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19794. get: function () {
  19795. return Camera._RIG_MODE_WEBVR;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. /**
  19801. * Store current camera state (fov, position, etc..)
  19802. */
  19803. Camera.prototype.storeState = function () {
  19804. this._stateStored = true;
  19805. this._storedFov = this.fov;
  19806. return this;
  19807. };
  19808. /**
  19809. * Restores the camera state values if it has been stored. You must call storeState() first
  19810. */
  19811. Camera.prototype._restoreStateValues = function () {
  19812. if (!this._stateStored) {
  19813. return false;
  19814. }
  19815. this.fov = this._storedFov;
  19816. return true;
  19817. };
  19818. /**
  19819. * Restored camera state. You must call storeState() first
  19820. */
  19821. Camera.prototype.restoreState = function () {
  19822. if (this._restoreStateValues()) {
  19823. this.onRestoreStateObservable.notifyObservers(this);
  19824. return true;
  19825. }
  19826. return false;
  19827. };
  19828. Camera.prototype.getClassName = function () {
  19829. return "Camera";
  19830. };
  19831. /**
  19832. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19833. */
  19834. Camera.prototype.toString = function (fullDetails) {
  19835. var ret = "Name: " + this.name;
  19836. ret += ", type: " + this.getClassName();
  19837. if (this.animations) {
  19838. for (var i = 0; i < this.animations.length; i++) {
  19839. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19840. }
  19841. }
  19842. if (fullDetails) {
  19843. }
  19844. return ret;
  19845. };
  19846. Object.defineProperty(Camera.prototype, "globalPosition", {
  19847. get: function () {
  19848. return this._globalPosition;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Camera.prototype.getActiveMeshes = function () {
  19854. return this._activeMeshes;
  19855. };
  19856. Camera.prototype.isActiveMesh = function (mesh) {
  19857. return (this._activeMeshes.indexOf(mesh) !== -1);
  19858. };
  19859. //Cache
  19860. Camera.prototype._initCache = function () {
  19861. _super.prototype._initCache.call(this);
  19862. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19863. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19864. this._cache.mode = undefined;
  19865. this._cache.minZ = undefined;
  19866. this._cache.maxZ = undefined;
  19867. this._cache.fov = undefined;
  19868. this._cache.fovMode = undefined;
  19869. this._cache.aspectRatio = undefined;
  19870. this._cache.orthoLeft = undefined;
  19871. this._cache.orthoRight = undefined;
  19872. this._cache.orthoBottom = undefined;
  19873. this._cache.orthoTop = undefined;
  19874. this._cache.renderWidth = undefined;
  19875. this._cache.renderHeight = undefined;
  19876. };
  19877. Camera.prototype._updateCache = function (ignoreParentClass) {
  19878. if (!ignoreParentClass) {
  19879. _super.prototype._updateCache.call(this);
  19880. }
  19881. this._cache.position.copyFrom(this.position);
  19882. this._cache.upVector.copyFrom(this.upVector);
  19883. };
  19884. // Synchronized
  19885. Camera.prototype._isSynchronized = function () {
  19886. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19887. };
  19888. Camera.prototype._isSynchronizedViewMatrix = function () {
  19889. if (!_super.prototype._isSynchronized.call(this))
  19890. return false;
  19891. return this._cache.position.equals(this.position)
  19892. && this._cache.upVector.equals(this.upVector)
  19893. && this.isSynchronizedWithParent();
  19894. };
  19895. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19896. var check = this._cache.mode === this.mode
  19897. && this._cache.minZ === this.minZ
  19898. && this._cache.maxZ === this.maxZ;
  19899. if (!check) {
  19900. return false;
  19901. }
  19902. var engine = this.getEngine();
  19903. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19904. check = this._cache.fov === this.fov
  19905. && this._cache.fovMode === this.fovMode
  19906. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19907. }
  19908. else {
  19909. check = this._cache.orthoLeft === this.orthoLeft
  19910. && this._cache.orthoRight === this.orthoRight
  19911. && this._cache.orthoBottom === this.orthoBottom
  19912. && this._cache.orthoTop === this.orthoTop
  19913. && this._cache.renderWidth === engine.getRenderWidth()
  19914. && this._cache.renderHeight === engine.getRenderHeight();
  19915. }
  19916. return check;
  19917. };
  19918. // Controls
  19919. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19920. };
  19921. Camera.prototype.detachControl = function (element) {
  19922. };
  19923. Camera.prototype.update = function () {
  19924. this._checkInputs();
  19925. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19926. this._updateRigCameras();
  19927. }
  19928. };
  19929. Camera.prototype._checkInputs = function () {
  19930. this.onAfterCheckInputsObservable.notifyObservers(this);
  19931. };
  19932. Object.defineProperty(Camera.prototype, "rigCameras", {
  19933. get: function () {
  19934. return this._rigCameras;
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19940. get: function () {
  19941. return this._rigPostProcess;
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19947. // invalidate framebuffer
  19948. if (this._postProcesses.length > 0) {
  19949. this._postProcesses[0].markTextureDirty();
  19950. }
  19951. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19952. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19953. var cam = this._rigCameras[i];
  19954. var rigPostProcess = cam._rigPostProcess;
  19955. // for VR rig, there does not have to be a post process
  19956. if (rigPostProcess) {
  19957. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19958. if (isPass) {
  19959. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19960. cam.isIntermediate = this._postProcesses.length === 0;
  19961. }
  19962. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19963. rigPostProcess.markTextureDirty();
  19964. }
  19965. else {
  19966. cam._postProcesses = this._postProcesses.slice(0);
  19967. }
  19968. }
  19969. };
  19970. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19971. if (insertAt === void 0) { insertAt = null; }
  19972. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19973. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19974. return 0;
  19975. }
  19976. if (insertAt == null || insertAt < 0) {
  19977. this._postProcesses.push(postProcess);
  19978. }
  19979. else {
  19980. this._postProcesses.splice(insertAt, 0, postProcess);
  19981. }
  19982. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19983. return this._postProcesses.indexOf(postProcess);
  19984. };
  19985. Camera.prototype.detachPostProcess = function (postProcess) {
  19986. var idx = this._postProcesses.indexOf(postProcess);
  19987. if (idx !== -1) {
  19988. this._postProcesses.splice(idx, 1);
  19989. }
  19990. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19991. };
  19992. Camera.prototype.getWorldMatrix = function () {
  19993. if (!this._worldMatrix) {
  19994. this._worldMatrix = BABYLON.Matrix.Identity();
  19995. }
  19996. var viewMatrix = this.getViewMatrix();
  19997. viewMatrix.invertToRef(this._worldMatrix);
  19998. return this._worldMatrix;
  19999. };
  20000. Camera.prototype._getViewMatrix = function () {
  20001. return BABYLON.Matrix.Identity();
  20002. };
  20003. Camera.prototype.getViewMatrix = function (force) {
  20004. if (!force && this._isSynchronizedViewMatrix()) {
  20005. return this._computedViewMatrix;
  20006. }
  20007. this.updateCache();
  20008. this._computedViewMatrix = this._getViewMatrix();
  20009. this._currentRenderId = this.getScene().getRenderId();
  20010. this._refreshFrustumPlanes = true;
  20011. if (!this.parent || !this.parent.getWorldMatrix) {
  20012. this._globalPosition.copyFrom(this.position);
  20013. }
  20014. else {
  20015. if (!this._worldMatrix) {
  20016. this._worldMatrix = BABYLON.Matrix.Identity();
  20017. }
  20018. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20019. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20020. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20021. this._computedViewMatrix.invert();
  20022. this._markSyncedWithParent();
  20023. }
  20024. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20025. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20026. }
  20027. this.onViewMatrixChangedObservable.notifyObservers(this);
  20028. return this._computedViewMatrix;
  20029. };
  20030. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20031. this._doNotComputeProjectionMatrix = true;
  20032. if (projection !== undefined) {
  20033. this._projectionMatrix = projection;
  20034. }
  20035. };
  20036. ;
  20037. Camera.prototype.unfreezeProjectionMatrix = function () {
  20038. this._doNotComputeProjectionMatrix = false;
  20039. };
  20040. ;
  20041. Camera.prototype.getProjectionMatrix = function (force) {
  20042. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20043. return this._projectionMatrix;
  20044. }
  20045. // Cache
  20046. this._cache.mode = this.mode;
  20047. this._cache.minZ = this.minZ;
  20048. this._cache.maxZ = this.maxZ;
  20049. // Matrix
  20050. this._refreshFrustumPlanes = true;
  20051. var engine = this.getEngine();
  20052. var scene = this.getScene();
  20053. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20054. this._cache.fov = this.fov;
  20055. this._cache.fovMode = this.fovMode;
  20056. this._cache.aspectRatio = engine.getAspectRatio(this);
  20057. if (this.minZ <= 0) {
  20058. this.minZ = 0.1;
  20059. }
  20060. if (scene.useRightHandedSystem) {
  20061. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20062. }
  20063. else {
  20064. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20065. }
  20066. }
  20067. else {
  20068. var halfWidth = engine.getRenderWidth() / 2.0;
  20069. var halfHeight = engine.getRenderHeight() / 2.0;
  20070. if (scene.useRightHandedSystem) {
  20071. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20072. }
  20073. else {
  20074. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20075. }
  20076. this._cache.orthoLeft = this.orthoLeft;
  20077. this._cache.orthoRight = this.orthoRight;
  20078. this._cache.orthoBottom = this.orthoBottom;
  20079. this._cache.orthoTop = this.orthoTop;
  20080. this._cache.renderWidth = engine.getRenderWidth();
  20081. this._cache.renderHeight = engine.getRenderHeight();
  20082. }
  20083. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20084. return this._projectionMatrix;
  20085. };
  20086. Camera.prototype.getTranformationMatrix = function () {
  20087. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20088. return this._transformMatrix;
  20089. };
  20090. Camera.prototype.updateFrustumPlanes = function () {
  20091. if (!this._refreshFrustumPlanes) {
  20092. return;
  20093. }
  20094. this.getTranformationMatrix();
  20095. if (!this._frustumPlanes) {
  20096. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20097. }
  20098. else {
  20099. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20100. }
  20101. this._refreshFrustumPlanes = false;
  20102. };
  20103. Camera.prototype.isInFrustum = function (target) {
  20104. this.updateFrustumPlanes();
  20105. return target.isInFrustum(this._frustumPlanes);
  20106. };
  20107. Camera.prototype.isCompletelyInFrustum = function (target) {
  20108. this.updateFrustumPlanes();
  20109. return target.isCompletelyInFrustum(this._frustumPlanes);
  20110. };
  20111. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20112. if (length === void 0) { length = 100; }
  20113. if (!transform) {
  20114. transform = this.getWorldMatrix();
  20115. }
  20116. if (!origin) {
  20117. origin = this.position;
  20118. }
  20119. var forward = new BABYLON.Vector3(0, 0, 1);
  20120. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20121. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20122. return new BABYLON.Ray(origin, direction, length);
  20123. };
  20124. Camera.prototype.dispose = function () {
  20125. // Observables
  20126. this.onViewMatrixChangedObservable.clear();
  20127. this.onProjectionMatrixChangedObservable.clear();
  20128. this.onAfterCheckInputsObservable.clear();
  20129. this.onRestoreStateObservable.clear();
  20130. // Inputs
  20131. if (this.inputs) {
  20132. this.inputs.clear();
  20133. }
  20134. // Animations
  20135. this.getScene().stopAnimation(this);
  20136. // Remove from scene
  20137. this.getScene().removeCamera(this);
  20138. while (this._rigCameras.length > 0) {
  20139. var camera = this._rigCameras.pop();
  20140. if (camera) {
  20141. camera.dispose();
  20142. }
  20143. }
  20144. // Postprocesses
  20145. if (this._rigPostProcess) {
  20146. this._rigPostProcess.dispose(this);
  20147. this._rigPostProcess = null;
  20148. this._postProcesses = [];
  20149. }
  20150. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20151. this._rigPostProcess = null;
  20152. this._postProcesses = [];
  20153. }
  20154. else {
  20155. var i = this._postProcesses.length;
  20156. while (--i >= 0) {
  20157. this._postProcesses[i].dispose(this);
  20158. }
  20159. }
  20160. // Render targets
  20161. var i = this.customRenderTargets.length;
  20162. while (--i >= 0) {
  20163. this.customRenderTargets[i].dispose();
  20164. }
  20165. this.customRenderTargets = [];
  20166. // Active Meshes
  20167. this._activeMeshes.dispose();
  20168. _super.prototype.dispose.call(this);
  20169. };
  20170. Object.defineProperty(Camera.prototype, "leftCamera", {
  20171. // ---- Camera rigs section ----
  20172. get: function () {
  20173. if (this._rigCameras.length < 1) {
  20174. return null;
  20175. }
  20176. return this._rigCameras[0];
  20177. },
  20178. enumerable: true,
  20179. configurable: true
  20180. });
  20181. Object.defineProperty(Camera.prototype, "rightCamera", {
  20182. get: function () {
  20183. if (this._rigCameras.length < 2) {
  20184. return null;
  20185. }
  20186. return this._rigCameras[1];
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Camera.prototype.getLeftTarget = function () {
  20192. if (this._rigCameras.length < 1) {
  20193. return null;
  20194. }
  20195. return this._rigCameras[0].getTarget();
  20196. };
  20197. Camera.prototype.getRightTarget = function () {
  20198. if (this._rigCameras.length < 2) {
  20199. return null;
  20200. }
  20201. return this._rigCameras[1].getTarget();
  20202. };
  20203. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20204. if (this.cameraRigMode === mode) {
  20205. return;
  20206. }
  20207. while (this._rigCameras.length > 0) {
  20208. var camera = this._rigCameras.pop();
  20209. if (camera) {
  20210. camera.dispose();
  20211. }
  20212. }
  20213. this.cameraRigMode = mode;
  20214. this._cameraRigParams = {};
  20215. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20216. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20217. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20218. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20219. // create the rig cameras, unless none
  20220. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20221. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20222. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20223. if (leftCamera && rightCamera) {
  20224. this._rigCameras.push(leftCamera);
  20225. this._rigCameras.push(rightCamera);
  20226. }
  20227. }
  20228. switch (this.cameraRigMode) {
  20229. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20230. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20231. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20232. break;
  20233. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20234. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20235. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20236. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20237. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20238. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20239. break;
  20240. case Camera.RIG_MODE_VR:
  20241. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20242. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20243. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20244. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20245. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20246. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20247. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20248. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20249. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20250. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20251. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20252. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20253. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20254. if (metrics.compensateDistortion) {
  20255. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20256. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20257. }
  20258. break;
  20259. case Camera.RIG_MODE_WEBVR:
  20260. if (rigParams.vrDisplay) {
  20261. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20262. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20263. //Left eye
  20264. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20265. this._rigCameras[0].setCameraRigParameter("left", true);
  20266. //leaving this for future reference
  20267. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20268. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20269. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20270. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20271. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20272. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20273. this._rigCameras[0].parent = this;
  20274. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20275. //Right eye
  20276. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20277. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20278. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20279. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20280. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20281. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20282. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20283. this._rigCameras[1].parent = this;
  20284. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20285. if (Camera.UseAlternateWebVRRendering) {
  20286. this._rigCameras[1]._skipRendering = true;
  20287. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20288. }
  20289. }
  20290. break;
  20291. }
  20292. this._cascadePostProcessesToRigCams();
  20293. this.update();
  20294. };
  20295. Camera.prototype._getVRProjectionMatrix = function () {
  20296. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20297. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20298. return this._projectionMatrix;
  20299. };
  20300. Camera.prototype._updateCameraRotationMatrix = function () {
  20301. //Here for WebVR
  20302. };
  20303. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20304. //Here for WebVR
  20305. };
  20306. /**
  20307. * This function MUST be overwritten by the different WebVR cameras available.
  20308. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20309. */
  20310. Camera.prototype._getWebVRProjectionMatrix = function () {
  20311. return BABYLON.Matrix.Identity();
  20312. };
  20313. /**
  20314. * This function MUST be overwritten by the different WebVR cameras available.
  20315. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20316. */
  20317. Camera.prototype._getWebVRViewMatrix = function () {
  20318. return BABYLON.Matrix.Identity();
  20319. };
  20320. Camera.prototype.setCameraRigParameter = function (name, value) {
  20321. if (!this._cameraRigParams) {
  20322. this._cameraRigParams = {};
  20323. }
  20324. this._cameraRigParams[name] = value;
  20325. //provisionnally:
  20326. if (name === "interaxialDistance") {
  20327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20328. }
  20329. };
  20330. /**
  20331. * needs to be overridden by children so sub has required properties to be copied
  20332. */
  20333. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20334. return null;
  20335. };
  20336. /**
  20337. * May need to be overridden by children
  20338. */
  20339. Camera.prototype._updateRigCameras = function () {
  20340. for (var i = 0; i < this._rigCameras.length; i++) {
  20341. this._rigCameras[i].minZ = this.minZ;
  20342. this._rigCameras[i].maxZ = this.maxZ;
  20343. this._rigCameras[i].fov = this.fov;
  20344. }
  20345. // only update viewport when ANAGLYPH
  20346. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20347. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20348. }
  20349. };
  20350. Camera.prototype._setupInputs = function () {
  20351. };
  20352. Camera.prototype.serialize = function () {
  20353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20354. // Type
  20355. serializationObject.type = this.getClassName();
  20356. // Parent
  20357. if (this.parent) {
  20358. serializationObject.parentId = this.parent.id;
  20359. }
  20360. if (this.inputs) {
  20361. this.inputs.serialize(serializationObject);
  20362. }
  20363. // Animations
  20364. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20365. serializationObject.ranges = this.serializeAnimationRanges();
  20366. return serializationObject;
  20367. };
  20368. Camera.prototype.clone = function (name) {
  20369. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20370. };
  20371. Camera.prototype.getDirection = function (localAxis) {
  20372. var result = BABYLON.Vector3.Zero();
  20373. this.getDirectionToRef(localAxis, result);
  20374. return result;
  20375. };
  20376. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20377. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20378. };
  20379. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20380. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20381. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20382. switch (type) {
  20383. case "ArcRotateCamera":
  20384. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20385. case "DeviceOrientationCamera":
  20386. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20387. case "FollowCamera":
  20388. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20389. case "ArcFollowCamera":
  20390. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20391. case "GamepadCamera":
  20392. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20393. case "TouchCamera":
  20394. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20395. case "VirtualJoysticksCamera":
  20396. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20397. case "WebVRFreeCamera":
  20398. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20399. case "WebVRGamepadCamera":
  20400. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20401. case "VRDeviceOrientationFreeCamera":
  20402. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20403. case "VRDeviceOrientationGamepadCamera":
  20404. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20405. case "AnaglyphArcRotateCamera":
  20406. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20407. case "AnaglyphFreeCamera":
  20408. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20409. case "AnaglyphGamepadCamera":
  20410. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20411. case "AnaglyphUniversalCamera":
  20412. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20413. case "StereoscopicArcRotateCamera":
  20414. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20415. case "StereoscopicFreeCamera":
  20416. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20417. case "StereoscopicGamepadCamera":
  20418. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20419. case "StereoscopicUniversalCamera":
  20420. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20421. case "FreeCamera":// Forcing Universal here
  20422. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20423. default:// Universal Camera is the default value
  20424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20425. }
  20426. };
  20427. Camera.prototype.computeWorldMatrix = function () {
  20428. return this.getWorldMatrix();
  20429. };
  20430. Camera.Parse = function (parsedCamera, scene) {
  20431. var type = parsedCamera.type;
  20432. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20433. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20434. // Parent
  20435. if (parsedCamera.parentId) {
  20436. camera._waitingParentId = parsedCamera.parentId;
  20437. }
  20438. //If camera has an input manager, let it parse inputs settings
  20439. if (camera.inputs) {
  20440. camera.inputs.parse(parsedCamera);
  20441. camera._setupInputs();
  20442. }
  20443. if (camera.setPosition) {
  20444. camera.position.copyFromFloats(0, 0, 0);
  20445. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20446. }
  20447. // Target
  20448. if (parsedCamera.target) {
  20449. if (camera.setTarget) {
  20450. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20451. }
  20452. }
  20453. // Apply 3d rig, when found
  20454. if (parsedCamera.cameraRigMode) {
  20455. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20456. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20457. }
  20458. // Animations
  20459. if (parsedCamera.animations) {
  20460. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20461. var parsedAnimation = parsedCamera.animations[animationIndex];
  20462. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20463. }
  20464. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20465. }
  20466. if (parsedCamera.autoAnimate) {
  20467. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20468. }
  20469. return camera;
  20470. };
  20471. // Statics
  20472. Camera._PERSPECTIVE_CAMERA = 0;
  20473. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20474. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20475. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20476. Camera._RIG_MODE_NONE = 0;
  20477. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20478. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20480. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20481. Camera._RIG_MODE_VR = 20;
  20482. Camera._RIG_MODE_WEBVR = 21;
  20483. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20484. Camera.UseAlternateWebVRRendering = false;
  20485. __decorate([
  20486. BABYLON.serializeAsVector3()
  20487. ], Camera.prototype, "position", void 0);
  20488. __decorate([
  20489. BABYLON.serializeAsVector3()
  20490. ], Camera.prototype, "upVector", void 0);
  20491. __decorate([
  20492. BABYLON.serialize()
  20493. ], Camera.prototype, "orthoLeft", void 0);
  20494. __decorate([
  20495. BABYLON.serialize()
  20496. ], Camera.prototype, "orthoRight", void 0);
  20497. __decorate([
  20498. BABYLON.serialize()
  20499. ], Camera.prototype, "orthoBottom", void 0);
  20500. __decorate([
  20501. BABYLON.serialize()
  20502. ], Camera.prototype, "orthoTop", void 0);
  20503. __decorate([
  20504. BABYLON.serialize()
  20505. ], Camera.prototype, "fov", void 0);
  20506. __decorate([
  20507. BABYLON.serialize()
  20508. ], Camera.prototype, "minZ", void 0);
  20509. __decorate([
  20510. BABYLON.serialize()
  20511. ], Camera.prototype, "maxZ", void 0);
  20512. __decorate([
  20513. BABYLON.serialize()
  20514. ], Camera.prototype, "inertia", void 0);
  20515. __decorate([
  20516. BABYLON.serialize()
  20517. ], Camera.prototype, "mode", void 0);
  20518. __decorate([
  20519. BABYLON.serialize()
  20520. ], Camera.prototype, "layerMask", void 0);
  20521. __decorate([
  20522. BABYLON.serialize()
  20523. ], Camera.prototype, "fovMode", void 0);
  20524. __decorate([
  20525. BABYLON.serialize()
  20526. ], Camera.prototype, "cameraRigMode", void 0);
  20527. __decorate([
  20528. BABYLON.serialize()
  20529. ], Camera.prototype, "interaxialDistance", void 0);
  20530. __decorate([
  20531. BABYLON.serialize()
  20532. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20533. return Camera;
  20534. }(BABYLON.Node));
  20535. BABYLON.Camera = Camera;
  20536. })(BABYLON || (BABYLON = {}));
  20537. //# sourceMappingURL=babylon.camera.js.map
  20538. var BABYLON;
  20539. (function (BABYLON) {
  20540. var RenderingManager = /** @class */ (function () {
  20541. function RenderingManager(scene) {
  20542. this._renderingGroups = new Array();
  20543. this._autoClearDepthStencil = {};
  20544. this._customOpaqueSortCompareFn = {};
  20545. this._customAlphaTestSortCompareFn = {};
  20546. this._customTransparentSortCompareFn = {};
  20547. this._renderinGroupInfo = null;
  20548. this._scene = scene;
  20549. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20550. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20551. }
  20552. }
  20553. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20554. if (depth === void 0) { depth = true; }
  20555. if (stencil === void 0) { stencil = true; }
  20556. if (this._depthStencilBufferAlreadyCleaned) {
  20557. return;
  20558. }
  20559. this._scene.getEngine().clear(null, false, depth, stencil);
  20560. this._depthStencilBufferAlreadyCleaned = true;
  20561. };
  20562. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20563. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20564. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20565. var info = null;
  20566. if (observable) {
  20567. if (!this._renderinGroupInfo) {
  20568. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20569. }
  20570. info = this._renderinGroupInfo;
  20571. info.scene = this._scene;
  20572. info.camera = this._scene.activeCamera;
  20573. }
  20574. // Dispatch sprites
  20575. if (renderSprites) {
  20576. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20577. var manager = this._scene.spriteManagers[index];
  20578. this.dispatchSprites(manager);
  20579. }
  20580. }
  20581. // Render
  20582. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20583. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20584. var renderingGroup = this._renderingGroups[index];
  20585. if (!renderingGroup && !observable)
  20586. continue;
  20587. var renderingGroupMask = 0;
  20588. // Fire PRECLEAR stage
  20589. if (observable && info) {
  20590. renderingGroupMask = Math.pow(2, index);
  20591. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20592. info.renderingGroupId = index;
  20593. observable.notifyObservers(info, renderingGroupMask);
  20594. }
  20595. // Clear depth/stencil if needed
  20596. if (RenderingManager.AUTOCLEAR) {
  20597. var autoClear = this._autoClearDepthStencil[index];
  20598. if (autoClear && autoClear.autoClear) {
  20599. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20600. }
  20601. }
  20602. if (observable && info) {
  20603. // Fire PREOPAQUE stage
  20604. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20605. observable.notifyObservers(info, renderingGroupMask);
  20606. // Fire PRETRANSPARENT stage
  20607. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20608. observable.notifyObservers(info, renderingGroupMask);
  20609. }
  20610. if (renderingGroup)
  20611. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20612. // Fire POSTTRANSPARENT stage
  20613. if (observable && info) {
  20614. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20615. observable.notifyObservers(info, renderingGroupMask);
  20616. }
  20617. }
  20618. };
  20619. RenderingManager.prototype.reset = function () {
  20620. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20621. var renderingGroup = this._renderingGroups[index];
  20622. if (renderingGroup) {
  20623. renderingGroup.prepare();
  20624. }
  20625. }
  20626. };
  20627. RenderingManager.prototype.dispose = function () {
  20628. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20629. var renderingGroup = this._renderingGroups[index];
  20630. if (renderingGroup) {
  20631. renderingGroup.dispose();
  20632. }
  20633. }
  20634. this._renderingGroups.length = 0;
  20635. };
  20636. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20637. if (this._renderingGroups[renderingGroupId] === undefined) {
  20638. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20639. }
  20640. };
  20641. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20642. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20643. this._prepareRenderingGroup(renderingGroupId);
  20644. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20645. };
  20646. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20647. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20648. this._prepareRenderingGroup(renderingGroupId);
  20649. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20650. };
  20651. /**
  20652. * @param subMesh The submesh to dispatch
  20653. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20654. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20655. */
  20656. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20657. if (mesh === undefined) {
  20658. mesh = subMesh.getMesh();
  20659. }
  20660. var renderingGroupId = mesh.renderingGroupId || 0;
  20661. this._prepareRenderingGroup(renderingGroupId);
  20662. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20663. };
  20664. /**
  20665. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20666. * This allowed control for front to back rendering or reversly depending of the special needs.
  20667. *
  20668. * @param renderingGroupId The rendering group id corresponding to its index
  20669. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20670. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20671. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20672. */
  20673. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20674. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20675. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20676. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20677. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20678. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20679. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20680. if (this._renderingGroups[renderingGroupId]) {
  20681. var group = this._renderingGroups[renderingGroupId];
  20682. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20683. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20684. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20685. }
  20686. };
  20687. /**
  20688. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20689. *
  20690. * @param renderingGroupId The rendering group id corresponding to its index
  20691. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20692. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20693. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20694. */
  20695. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20696. if (depth === void 0) { depth = true; }
  20697. if (stencil === void 0) { stencil = true; }
  20698. this._autoClearDepthStencil[renderingGroupId] = {
  20699. autoClear: autoClearDepthStencil,
  20700. depth: depth,
  20701. stencil: stencil
  20702. };
  20703. };
  20704. /**
  20705. * The max id used for rendering groups (not included)
  20706. */
  20707. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20708. /**
  20709. * The min id used for rendering groups (included)
  20710. */
  20711. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20712. /**
  20713. * Used to globally prevent autoclearing scenes.
  20714. */
  20715. RenderingManager.AUTOCLEAR = true;
  20716. return RenderingManager;
  20717. }());
  20718. BABYLON.RenderingManager = RenderingManager;
  20719. })(BABYLON || (BABYLON = {}));
  20720. //# sourceMappingURL=babylon.renderingManager.js.map
  20721. var BABYLON;
  20722. (function (BABYLON) {
  20723. var RenderingGroup = /** @class */ (function () {
  20724. /**
  20725. * Creates a new rendering group.
  20726. * @param index The rendering group index
  20727. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20728. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20729. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20730. */
  20731. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20732. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20733. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20734. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20735. this.index = index;
  20736. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20737. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20738. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20739. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20740. this._particleSystems = new BABYLON.SmartArray(256);
  20741. this._spriteManagers = new BABYLON.SmartArray(256);
  20742. this._edgesRenderers = new BABYLON.SmartArray(16);
  20743. this._scene = scene;
  20744. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20745. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20746. this.transparentSortCompareFn = transparentSortCompareFn;
  20747. }
  20748. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20749. /**
  20750. * Set the opaque sort comparison function.
  20751. * If null the sub meshes will be render in the order they were created
  20752. */
  20753. set: function (value) {
  20754. this._opaqueSortCompareFn = value;
  20755. if (value) {
  20756. this._renderOpaque = this.renderOpaqueSorted;
  20757. }
  20758. else {
  20759. this._renderOpaque = RenderingGroup.renderUnsorted;
  20760. }
  20761. },
  20762. enumerable: true,
  20763. configurable: true
  20764. });
  20765. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20766. /**
  20767. * Set the alpha test sort comparison function.
  20768. * If null the sub meshes will be render in the order they were created
  20769. */
  20770. set: function (value) {
  20771. this._alphaTestSortCompareFn = value;
  20772. if (value) {
  20773. this._renderAlphaTest = this.renderAlphaTestSorted;
  20774. }
  20775. else {
  20776. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20777. }
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20783. /**
  20784. * Set the transparent sort comparison function.
  20785. * If null the sub meshes will be render in the order they were created
  20786. */
  20787. set: function (value) {
  20788. if (value) {
  20789. this._transparentSortCompareFn = value;
  20790. }
  20791. else {
  20792. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20793. }
  20794. this._renderTransparent = this.renderTransparentSorted;
  20795. },
  20796. enumerable: true,
  20797. configurable: true
  20798. });
  20799. /**
  20800. * Render all the sub meshes contained in the group.
  20801. * @param customRenderFunction Used to override the default render behaviour of the group.
  20802. * @returns true if rendered some submeshes.
  20803. */
  20804. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20805. if (customRenderFunction) {
  20806. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20807. return;
  20808. }
  20809. var engine = this._scene.getEngine();
  20810. // Depth only
  20811. if (this._depthOnlySubMeshes.length !== 0) {
  20812. engine.setColorWrite(false);
  20813. this._renderAlphaTest(this._depthOnlySubMeshes);
  20814. engine.setColorWrite(true);
  20815. }
  20816. // Opaque
  20817. if (this._opaqueSubMeshes.length !== 0) {
  20818. this._renderOpaque(this._opaqueSubMeshes);
  20819. }
  20820. // Alpha test
  20821. if (this._alphaTestSubMeshes.length !== 0) {
  20822. this._renderAlphaTest(this._alphaTestSubMeshes);
  20823. }
  20824. var stencilState = engine.getStencilBuffer();
  20825. engine.setStencilBuffer(false);
  20826. // Sprites
  20827. if (renderSprites) {
  20828. this._renderSprites();
  20829. }
  20830. // Particles
  20831. if (renderParticles) {
  20832. this._renderParticles(activeMeshes);
  20833. }
  20834. if (this.onBeforeTransparentRendering) {
  20835. this.onBeforeTransparentRendering();
  20836. }
  20837. // Transparent
  20838. if (this._transparentSubMeshes.length !== 0) {
  20839. this._renderTransparent(this._transparentSubMeshes);
  20840. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20841. }
  20842. // Set back stencil to false in case it changes before the edge renderer.
  20843. engine.setStencilBuffer(false);
  20844. // Edges
  20845. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20846. this._edgesRenderers.data[edgesRendererIndex].render();
  20847. }
  20848. // Restore Stencil state.
  20849. engine.setStencilBuffer(stencilState);
  20850. };
  20851. /**
  20852. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20853. * @param subMeshes The submeshes to render
  20854. */
  20855. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20856. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20857. };
  20858. /**
  20859. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20860. * @param subMeshes The submeshes to render
  20861. */
  20862. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20863. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20864. };
  20865. /**
  20866. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20867. * @param subMeshes The submeshes to render
  20868. */
  20869. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20870. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20871. };
  20872. /**
  20873. * Renders the submeshes in a specified order.
  20874. * @param subMeshes The submeshes to sort before render
  20875. * @param sortCompareFn The comparison function use to sort
  20876. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20877. * @param transparent Specifies to activate blending if true
  20878. */
  20879. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20880. var subIndex = 0;
  20881. var subMesh;
  20882. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20883. for (; subIndex < subMeshes.length; subIndex++) {
  20884. subMesh = subMeshes.data[subIndex];
  20885. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20886. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20887. }
  20888. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20889. if (sortCompareFn) {
  20890. sortedArray.sort(sortCompareFn);
  20891. }
  20892. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20893. subMesh = sortedArray[subIndex];
  20894. if (transparent) {
  20895. var material = subMesh.getMaterial();
  20896. if (material && material.needDepthPrePass) {
  20897. var engine = material.getScene().getEngine();
  20898. engine.setColorWrite(false);
  20899. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20900. subMesh.render(false);
  20901. engine.setColorWrite(true);
  20902. }
  20903. }
  20904. subMesh.render(transparent);
  20905. }
  20906. };
  20907. /**
  20908. * Renders the submeshes in the order they were dispatched (no sort applied).
  20909. * @param subMeshes The submeshes to render
  20910. */
  20911. RenderingGroup.renderUnsorted = function (subMeshes) {
  20912. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20913. var submesh = subMeshes.data[subIndex];
  20914. submesh.render(false);
  20915. }
  20916. };
  20917. /**
  20918. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20919. * are rendered back to front if in the same alpha index.
  20920. *
  20921. * @param a The first submesh
  20922. * @param b The second submesh
  20923. * @returns The result of the comparison
  20924. */
  20925. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20926. // Alpha index first
  20927. if (a._alphaIndex > b._alphaIndex) {
  20928. return 1;
  20929. }
  20930. if (a._alphaIndex < b._alphaIndex) {
  20931. return -1;
  20932. }
  20933. // Then distance to camera
  20934. return RenderingGroup.backToFrontSortCompare(a, b);
  20935. };
  20936. /**
  20937. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20938. * are rendered back to front.
  20939. *
  20940. * @param a The first submesh
  20941. * @param b The second submesh
  20942. * @returns The result of the comparison
  20943. */
  20944. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20945. // Then distance to camera
  20946. if (a._distanceToCamera < b._distanceToCamera) {
  20947. return 1;
  20948. }
  20949. if (a._distanceToCamera > b._distanceToCamera) {
  20950. return -1;
  20951. }
  20952. return 0;
  20953. };
  20954. /**
  20955. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20956. * are rendered front to back (prevent overdraw).
  20957. *
  20958. * @param a The first submesh
  20959. * @param b The second submesh
  20960. * @returns The result of the comparison
  20961. */
  20962. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20963. // Then distance to camera
  20964. if (a._distanceToCamera < b._distanceToCamera) {
  20965. return -1;
  20966. }
  20967. if (a._distanceToCamera > b._distanceToCamera) {
  20968. return 1;
  20969. }
  20970. return 0;
  20971. };
  20972. /**
  20973. * Resets the different lists of submeshes to prepare a new frame.
  20974. */
  20975. RenderingGroup.prototype.prepare = function () {
  20976. this._opaqueSubMeshes.reset();
  20977. this._transparentSubMeshes.reset();
  20978. this._alphaTestSubMeshes.reset();
  20979. this._depthOnlySubMeshes.reset();
  20980. this._particleSystems.reset();
  20981. this._spriteManagers.reset();
  20982. this._edgesRenderers.reset();
  20983. };
  20984. RenderingGroup.prototype.dispose = function () {
  20985. this._opaqueSubMeshes.dispose();
  20986. this._transparentSubMeshes.dispose();
  20987. this._alphaTestSubMeshes.dispose();
  20988. this._depthOnlySubMeshes.dispose();
  20989. this._particleSystems.dispose();
  20990. this._spriteManagers.dispose();
  20991. this._edgesRenderers.dispose();
  20992. };
  20993. /**
  20994. * Inserts the submesh in its correct queue depending on its material.
  20995. * @param subMesh The submesh to dispatch
  20996. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20997. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20998. */
  20999. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21000. // Get mesh and materials if not provided
  21001. if (mesh === undefined) {
  21002. mesh = subMesh.getMesh();
  21003. }
  21004. if (material === undefined) {
  21005. material = subMesh.getMaterial();
  21006. }
  21007. if (material === null || material === undefined) {
  21008. return;
  21009. }
  21010. if (material.needAlphaBlendingForMesh(mesh)) {
  21011. this._transparentSubMeshes.push(subMesh);
  21012. }
  21013. else if (material.needAlphaTesting()) {
  21014. if (material.needDepthPrePass) {
  21015. this._depthOnlySubMeshes.push(subMesh);
  21016. }
  21017. this._alphaTestSubMeshes.push(subMesh);
  21018. }
  21019. else {
  21020. if (material.needDepthPrePass) {
  21021. this._depthOnlySubMeshes.push(subMesh);
  21022. }
  21023. this._opaqueSubMeshes.push(subMesh); // Opaque
  21024. }
  21025. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21026. this._edgesRenderers.push(mesh._edgesRenderer);
  21027. }
  21028. };
  21029. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21030. this._spriteManagers.push(spriteManager);
  21031. };
  21032. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21033. this._particleSystems.push(particleSystem);
  21034. };
  21035. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21036. if (this._particleSystems.length === 0) {
  21037. return;
  21038. }
  21039. // Particles
  21040. var activeCamera = this._scene.activeCamera;
  21041. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21042. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21043. var particleSystem = this._particleSystems.data[particleIndex];
  21044. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21045. continue;
  21046. }
  21047. var emitter = particleSystem.emitter;
  21048. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21049. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21050. }
  21051. }
  21052. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21053. };
  21054. RenderingGroup.prototype._renderSprites = function () {
  21055. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21056. return;
  21057. }
  21058. // Sprites
  21059. var activeCamera = this._scene.activeCamera;
  21060. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21061. for (var id = 0; id < this._spriteManagers.length; id++) {
  21062. var spriteManager = this._spriteManagers.data[id];
  21063. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21064. spriteManager.render();
  21065. }
  21066. }
  21067. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21068. };
  21069. return RenderingGroup;
  21070. }());
  21071. BABYLON.RenderingGroup = RenderingGroup;
  21072. })(BABYLON || (BABYLON = {}));
  21073. //# sourceMappingURL=babylon.renderingGroup.js.map
  21074. var BABYLON;
  21075. (function (BABYLON) {
  21076. var ClickInfo = /** @class */ (function () {
  21077. function ClickInfo() {
  21078. this._singleClick = false;
  21079. this._doubleClick = false;
  21080. this._hasSwiped = false;
  21081. this._ignore = false;
  21082. }
  21083. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21084. get: function () {
  21085. return this._singleClick;
  21086. },
  21087. set: function (b) {
  21088. this._singleClick = b;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21094. get: function () {
  21095. return this._doubleClick;
  21096. },
  21097. set: function (b) {
  21098. this._doubleClick = b;
  21099. },
  21100. enumerable: true,
  21101. configurable: true
  21102. });
  21103. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21104. get: function () {
  21105. return this._hasSwiped;
  21106. },
  21107. set: function (b) {
  21108. this._hasSwiped = b;
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21114. get: function () {
  21115. return this._ignore;
  21116. },
  21117. set: function (b) {
  21118. this._ignore = b;
  21119. },
  21120. enumerable: true,
  21121. configurable: true
  21122. });
  21123. return ClickInfo;
  21124. }());
  21125. /**
  21126. * This class is used by the onRenderingGroupObservable
  21127. */
  21128. var RenderingGroupInfo = /** @class */ (function () {
  21129. function RenderingGroupInfo() {
  21130. }
  21131. /**
  21132. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21133. * This stage will be fired no matter what
  21134. */
  21135. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21136. /**
  21137. * Called before opaque object are rendered.
  21138. * This stage will be fired only if there's 3D Opaque content to render
  21139. */
  21140. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21141. /**
  21142. * Called after the opaque objects are rendered and before the transparent ones
  21143. * This stage will be fired only if there's 3D transparent content to render
  21144. */
  21145. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21146. /**
  21147. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21148. * This stage will be fired no matter what
  21149. */
  21150. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21151. return RenderingGroupInfo;
  21152. }());
  21153. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21154. /**
  21155. * Represents a scene to be rendered by the engine.
  21156. * @see http://doc.babylonjs.com/page.php?p=21911
  21157. */
  21158. var Scene = /** @class */ (function () {
  21159. /**
  21160. * @constructor
  21161. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21162. */
  21163. function Scene(engine) {
  21164. // Members
  21165. this.autoClear = true;
  21166. this.autoClearDepthAndStencil = true;
  21167. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21168. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21169. this.forceWireframe = false;
  21170. this._forcePointsCloud = false;
  21171. this.forceShowBoundingBoxes = false;
  21172. this.animationsEnabled = true;
  21173. this.useConstantAnimationDeltaTime = false;
  21174. this.constantlyUpdateMeshUnderPointer = false;
  21175. this.hoverCursor = "pointer";
  21176. this.defaultCursor = "";
  21177. /**
  21178. * This is used to call preventDefault() on pointer down
  21179. * in order to block unwanted artifacts like system double clicks
  21180. */
  21181. this.preventDefaultOnPointerDown = true;
  21182. // Metadata
  21183. this.metadata = null;
  21184. /**
  21185. * An event triggered when the scene is disposed.
  21186. * @type {BABYLON.Observable}
  21187. */
  21188. this.onDisposeObservable = new BABYLON.Observable();
  21189. /**
  21190. * An event triggered before rendering the scene (right after animations and physics)
  21191. * @type {BABYLON.Observable}
  21192. */
  21193. this.onBeforeRenderObservable = new BABYLON.Observable();
  21194. /**
  21195. * An event triggered after rendering the scene
  21196. * @type {BABYLON.Observable}
  21197. */
  21198. this.onAfterRenderObservable = new BABYLON.Observable();
  21199. /**
  21200. * An event triggered before animating the scene
  21201. * @type {BABYLON.Observable}
  21202. */
  21203. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21204. /**
  21205. * An event triggered after animations processing
  21206. * @type {BABYLON.Observable}
  21207. */
  21208. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21209. /**
  21210. * An event triggered before draw calls are ready to be sent
  21211. * @type {BABYLON.Observable}
  21212. */
  21213. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21214. /**
  21215. * An event triggered after draw calls have been sent
  21216. * @type {BABYLON.Observable}
  21217. */
  21218. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21219. /**
  21220. * An event triggered when physic simulation is about to be run
  21221. * @type {BABYLON.Observable}
  21222. */
  21223. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21224. /**
  21225. * An event triggered when physic simulation has been done
  21226. * @type {BABYLON.Observable}
  21227. */
  21228. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21229. /**
  21230. * An event triggered when the scene is ready
  21231. * @type {BABYLON.Observable}
  21232. */
  21233. this.onReadyObservable = new BABYLON.Observable();
  21234. /**
  21235. * An event triggered before rendering a camera
  21236. * @type {BABYLON.Observable}
  21237. */
  21238. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21239. /**
  21240. * An event triggered after rendering a camera
  21241. * @type {BABYLON.Observable}
  21242. */
  21243. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21244. /**
  21245. * An event triggered when active meshes evaluation is about to start
  21246. * @type {BABYLON.Observable}
  21247. */
  21248. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21249. /**
  21250. * An event triggered when active meshes evaluation is done
  21251. * @type {BABYLON.Observable}
  21252. */
  21253. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21254. /**
  21255. * An event triggered when particles rendering is about to start
  21256. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21257. * @type {BABYLON.Observable}
  21258. */
  21259. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21260. /**
  21261. * An event triggered when particles rendering is done
  21262. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21263. * @type {BABYLON.Observable}
  21264. */
  21265. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21266. /**
  21267. * An event triggered when sprites rendering is about to start
  21268. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21269. * @type {BABYLON.Observable}
  21270. */
  21271. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21272. /**
  21273. * An event triggered when sprites rendering is done
  21274. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onDataLoadedObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered when a camera is created
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when a camera is removed
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onCameraRemovedObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when a light is created
  21295. * @type {BABYLON.Observable}
  21296. */
  21297. this.onNewLightAddedObservable = new BABYLON.Observable();
  21298. /**
  21299. * An event triggered when a light is removed
  21300. * @type {BABYLON.Observable}
  21301. */
  21302. this.onLightRemovedObservable = new BABYLON.Observable();
  21303. /**
  21304. * An event triggered when a geometry is created
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered when a geometry is removed
  21310. * @type {BABYLON.Observable}
  21311. */
  21312. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21313. /**
  21314. * An event triggered when a transform node is created
  21315. * @type {BABYLON.Observable}
  21316. */
  21317. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21318. /**
  21319. * An event triggered when a transform node is removed
  21320. * @type {BABYLON.Observable}
  21321. */
  21322. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21323. /**
  21324. * An event triggered when a mesh is created
  21325. * @type {BABYLON.Observable}
  21326. */
  21327. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21328. /**
  21329. * An event triggered when a mesh is removed
  21330. * @type {BABYLON.Observable}
  21331. */
  21332. this.onMeshRemovedObservable = new BABYLON.Observable();
  21333. /**
  21334. * An event triggered when render targets are about to be rendered
  21335. * Can happen multiple times per frame.
  21336. * @type {BABYLON.Observable}
  21337. */
  21338. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21339. /**
  21340. * An event triggered when render targets were rendered.
  21341. * Can happen multiple times per frame.
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered before calculating deterministic simulation step
  21347. * @type {BABYLON.Observable}
  21348. */
  21349. this.onBeforeStepObservable = new BABYLON.Observable();
  21350. /**
  21351. * An event triggered after calculating deterministic simulation step
  21352. * @type {BABYLON.Observable}
  21353. */
  21354. this.onAfterStepObservable = new BABYLON.Observable();
  21355. /**
  21356. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21357. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21358. * 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)
  21359. */
  21360. this.onRenderingGroupObservable = new BABYLON.Observable();
  21361. // Animations
  21362. this.animations = [];
  21363. /**
  21364. * 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).
  21365. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21366. */
  21367. this.onPrePointerObservable = new BABYLON.Observable();
  21368. /**
  21369. * Observable event triggered each time an input event is received from the rendering canvas
  21370. */
  21371. this.onPointerObservable = new BABYLON.Observable();
  21372. this._meshPickProceed = false;
  21373. this._currentPickResult = null;
  21374. this._previousPickResult = null;
  21375. this._totalPointersPressed = 0;
  21376. this._doubleClickOccured = false;
  21377. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21378. this.cameraToUseForPointers = null;
  21379. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21380. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21381. this._startingPointerTime = 0;
  21382. this._previousStartingPointerTime = 0;
  21383. // Deterministic lockstep
  21384. this._timeAccumulator = 0;
  21385. this._currentStepId = 0;
  21386. this._currentInternalStep = 0;
  21387. // Keyboard
  21388. /**
  21389. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21390. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21391. */
  21392. this.onPreKeyboardObservable = new BABYLON.Observable();
  21393. /**
  21394. * Observable event triggered each time an keyboard event is received from the hosting window
  21395. */
  21396. this.onKeyboardObservable = new BABYLON.Observable();
  21397. // Coordinate system
  21398. /**
  21399. * use right-handed coordinate system on this scene.
  21400. * @type {boolean}
  21401. */
  21402. this._useRightHandedSystem = false;
  21403. // Fog
  21404. this._fogEnabled = true;
  21405. this._fogMode = Scene.FOGMODE_NONE;
  21406. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21407. this.fogDensity = 0.1;
  21408. this.fogStart = 0;
  21409. this.fogEnd = 1000.0;
  21410. // Lights
  21411. /**
  21412. * is shadow enabled on this scene.
  21413. * @type {boolean}
  21414. */
  21415. this._shadowsEnabled = true;
  21416. /**
  21417. * is light enabled on this scene.
  21418. * @type {boolean}
  21419. */
  21420. this._lightsEnabled = true;
  21421. /**
  21422. * All of the lights added to this scene.
  21423. * @see BABYLON.Light
  21424. * @type {BABYLON.Light[]}
  21425. */
  21426. this.lights = new Array();
  21427. // Cameras
  21428. /** All of the cameras added to this scene. */
  21429. this.cameras = new Array();
  21430. /** All of the active cameras added to this scene. */
  21431. this.activeCameras = new Array();
  21432. // Meshes
  21433. /**
  21434. * All of the tranform nodes added to this scene.
  21435. * @see BABYLON.TransformNode
  21436. * @type {BABYLON.TransformNode[]}
  21437. */
  21438. this.transformNodes = new Array();
  21439. /**
  21440. * All of the (abstract) meshes added to this scene.
  21441. * @see BABYLON.AbstractMesh
  21442. * @type {BABYLON.AbstractMesh[]}
  21443. */
  21444. this.meshes = new Array();
  21445. /**
  21446. * All of the animation groups added to this scene.
  21447. * @see BABYLON.AnimationGroup
  21448. * @type {BABYLON.AnimationGroup[]}
  21449. */
  21450. this.animationGroups = new Array();
  21451. // Geometries
  21452. this._geometries = new Array();
  21453. this.materials = new Array();
  21454. this.multiMaterials = new Array();
  21455. // Textures
  21456. this._texturesEnabled = true;
  21457. this.textures = new Array();
  21458. // Particles
  21459. this.particlesEnabled = true;
  21460. this.particleSystems = new Array();
  21461. // Sprites
  21462. this.spritesEnabled = true;
  21463. this.spriteManagers = new Array();
  21464. /**
  21465. * The list of layers (background and foreground) of the scene.
  21466. */
  21467. this.layers = new Array();
  21468. /**
  21469. * The list of effect layers (highlights/glow) contained in the scene.
  21470. */
  21471. this.effectLayers = new Array();
  21472. // Skeletons
  21473. this._skeletonsEnabled = true;
  21474. this.skeletons = new Array();
  21475. // Morph targets
  21476. this.morphTargetManagers = new Array();
  21477. // Lens flares
  21478. this.lensFlaresEnabled = true;
  21479. this.lensFlareSystems = new Array();
  21480. // Collisions
  21481. this.collisionsEnabled = true;
  21482. /** Defines the gravity applied to this scene */
  21483. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21484. // Postprocesses
  21485. this.postProcesses = new Array();
  21486. this.postProcessesEnabled = true;
  21487. // Customs render targets
  21488. this.renderTargetsEnabled = true;
  21489. this.dumpNextRenderTargets = false;
  21490. this.customRenderTargets = new Array();
  21491. // Imported meshes
  21492. this.importedMeshesFiles = new Array();
  21493. // Probes
  21494. this.probesEnabled = true;
  21495. this.reflectionProbes = new Array();
  21496. this._actionManagers = new Array();
  21497. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21498. // Procedural textures
  21499. this.proceduralTexturesEnabled = true;
  21500. this._proceduralTextures = new Array();
  21501. this.soundTracks = new Array();
  21502. this._audioEnabled = true;
  21503. this._headphone = false;
  21504. // Performance counters
  21505. this._totalVertices = new BABYLON.PerfCounter();
  21506. this._activeIndices = new BABYLON.PerfCounter();
  21507. this._activeParticles = new BABYLON.PerfCounter();
  21508. this._activeBones = new BABYLON.PerfCounter();
  21509. this._animationTime = 0;
  21510. this.animationTimeScale = 1;
  21511. this._renderId = 0;
  21512. this._executeWhenReadyTimeoutId = -1;
  21513. this._intermediateRendering = false;
  21514. this._viewUpdateFlag = -1;
  21515. this._projectionUpdateFlag = -1;
  21516. this._alternateViewUpdateFlag = -1;
  21517. this._alternateProjectionUpdateFlag = -1;
  21518. this._toBeDisposed = new BABYLON.SmartArray(256);
  21519. this._activeRequests = new Array();
  21520. this._pendingData = new Array();
  21521. this._isDisposed = false;
  21522. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21523. this._activeMeshes = new BABYLON.SmartArray(256);
  21524. this._processedMaterials = new BABYLON.SmartArray(256);
  21525. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21526. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21527. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21528. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21529. this._activeAnimatables = new Array();
  21530. this._transformMatrix = BABYLON.Matrix.Zero();
  21531. this._useAlternateCameraConfiguration = false;
  21532. this._alternateRendering = false;
  21533. this.requireLightSorting = false;
  21534. this._depthRenderer = {};
  21535. this._activeMeshesFrozen = false;
  21536. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21537. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21538. this._engine.scenes.push(this);
  21539. this._uid = null;
  21540. this._renderingManager = new BABYLON.RenderingManager(this);
  21541. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21542. if (BABYLON.OutlineRenderer) {
  21543. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21544. }
  21545. if (BABYLON.Tools.IsWindowObjectExist()) {
  21546. this.attachControl();
  21547. }
  21548. //simplification queue
  21549. if (BABYLON.SimplificationQueue) {
  21550. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21551. }
  21552. //collision coordinator initialization. For now legacy per default.
  21553. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21554. // Uniform Buffer
  21555. this._createUbo();
  21556. // Default Image processing definition.
  21557. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21558. }
  21559. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21560. /** The fog is deactivated */
  21561. get: function () {
  21562. return Scene._FOGMODE_NONE;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21568. /** The fog density is following an exponential function */
  21569. get: function () {
  21570. return Scene._FOGMODE_EXP;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21576. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21577. get: function () {
  21578. return Scene._FOGMODE_EXP2;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21584. /** The fog density is following a linear function. */
  21585. get: function () {
  21586. return Scene._FOGMODE_LINEAR;
  21587. },
  21588. enumerable: true,
  21589. configurable: true
  21590. });
  21591. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21592. /**
  21593. * Texture used in all pbr material as the reflection texture.
  21594. * As in the majority of the scene they are the same (exception for multi room and so on),
  21595. * this is easier to reference from here than from all the materials.
  21596. */
  21597. get: function () {
  21598. return this._environmentTexture;
  21599. },
  21600. /**
  21601. * Texture used in all pbr material as the reflection texture.
  21602. * As in the majority of the scene they are the same (exception for multi room and so on),
  21603. * this is easier to set here than in all the materials.
  21604. */
  21605. set: function (value) {
  21606. if (this._environmentTexture === value) {
  21607. return;
  21608. }
  21609. this._environmentTexture = value;
  21610. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21616. /**
  21617. * Default image processing configuration used either in the rendering
  21618. * Forward main pass or through the imageProcessingPostProcess if present.
  21619. * As in the majority of the scene they are the same (exception for multi camera),
  21620. * this is easier to reference from here than from all the materials and post process.
  21621. *
  21622. * No setter as we it is a shared configuration, you can set the values instead.
  21623. */
  21624. get: function () {
  21625. return this._imageProcessingConfiguration;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21631. get: function () {
  21632. return this._forcePointsCloud;
  21633. },
  21634. set: function (value) {
  21635. if (this._forcePointsCloud === value) {
  21636. return;
  21637. }
  21638. this._forcePointsCloud = value;
  21639. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(Scene.prototype, "onDispose", {
  21645. /** A function to be executed when this scene is disposed. */
  21646. set: function (callback) {
  21647. if (this._onDisposeObserver) {
  21648. this.onDisposeObservable.remove(this._onDisposeObserver);
  21649. }
  21650. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Scene.prototype, "beforeRender", {
  21656. /** A function to be executed before rendering this scene */
  21657. set: function (callback) {
  21658. if (this._onBeforeRenderObserver) {
  21659. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21660. }
  21661. if (callback) {
  21662. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21663. }
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Scene.prototype, "afterRender", {
  21669. /** A function to be executed after rendering this scene */
  21670. set: function (callback) {
  21671. if (this._onAfterRenderObserver) {
  21672. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21673. }
  21674. if (callback) {
  21675. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21676. }
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21682. set: function (callback) {
  21683. if (this._onBeforeCameraRenderObserver) {
  21684. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21685. }
  21686. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21692. set: function (callback) {
  21693. if (this._onAfterCameraRenderObserver) {
  21694. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21695. }
  21696. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21702. get: function () {
  21703. if (!this._gamepadManager) {
  21704. this._gamepadManager = new BABYLON.GamepadManager(this);
  21705. }
  21706. return this._gamepadManager;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21712. get: function () {
  21713. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21719. get: function () {
  21720. return this._useRightHandedSystem;
  21721. },
  21722. set: function (value) {
  21723. if (this._useRightHandedSystem === value) {
  21724. return;
  21725. }
  21726. this._useRightHandedSystem = value;
  21727. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Scene.prototype.setStepId = function (newStepId) {
  21733. this._currentStepId = newStepId;
  21734. };
  21735. ;
  21736. Scene.prototype.getStepId = function () {
  21737. return this._currentStepId;
  21738. };
  21739. ;
  21740. Scene.prototype.getInternalStep = function () {
  21741. return this._currentInternalStep;
  21742. };
  21743. ;
  21744. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21745. get: function () {
  21746. return this._fogEnabled;
  21747. },
  21748. /**
  21749. * is fog enabled on this scene.
  21750. */
  21751. set: function (value) {
  21752. if (this._fogEnabled === value) {
  21753. return;
  21754. }
  21755. this._fogEnabled = value;
  21756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Scene.prototype, "fogMode", {
  21762. get: function () {
  21763. return this._fogMode;
  21764. },
  21765. set: function (value) {
  21766. if (this._fogMode === value) {
  21767. return;
  21768. }
  21769. this._fogMode = value;
  21770. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21776. get: function () {
  21777. return this._shadowsEnabled;
  21778. },
  21779. set: function (value) {
  21780. if (this._shadowsEnabled === value) {
  21781. return;
  21782. }
  21783. this._shadowsEnabled = value;
  21784. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21790. get: function () {
  21791. return this._lightsEnabled;
  21792. },
  21793. set: function (value) {
  21794. if (this._lightsEnabled === value) {
  21795. return;
  21796. }
  21797. this._lightsEnabled = value;
  21798. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21804. /** The default material used on meshes when no material is affected */
  21805. get: function () {
  21806. if (!this._defaultMaterial) {
  21807. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21808. }
  21809. return this._defaultMaterial;
  21810. },
  21811. /** The default material used on meshes when no material is affected */
  21812. set: function (value) {
  21813. this._defaultMaterial = value;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21819. get: function () {
  21820. return this._texturesEnabled;
  21821. },
  21822. set: function (value) {
  21823. if (this._texturesEnabled === value) {
  21824. return;
  21825. }
  21826. this._texturesEnabled = value;
  21827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21833. get: function () {
  21834. return this._skeletonsEnabled;
  21835. },
  21836. set: function (value) {
  21837. if (this._skeletonsEnabled === value) {
  21838. return;
  21839. }
  21840. this._skeletonsEnabled = value;
  21841. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21842. },
  21843. enumerable: true,
  21844. configurable: true
  21845. });
  21846. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21847. get: function () {
  21848. if (!this._postProcessRenderPipelineManager) {
  21849. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21850. }
  21851. return this._postProcessRenderPipelineManager;
  21852. },
  21853. enumerable: true,
  21854. configurable: true
  21855. });
  21856. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21857. get: function () {
  21858. if (!this._mainSoundTrack) {
  21859. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21860. }
  21861. return this._mainSoundTrack;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21867. get: function () {
  21868. return this._alternateRendering;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21874. get: function () {
  21875. return this._frustumPlanes;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21881. /**
  21882. * Gets the current geometry buffer associated to the scene.
  21883. */
  21884. get: function () {
  21885. return this._geometryBufferRenderer;
  21886. },
  21887. /**
  21888. * Sets the current geometry buffer for the scene.
  21889. */
  21890. set: function (geometryBufferRenderer) {
  21891. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21892. this._geometryBufferRenderer = geometryBufferRenderer;
  21893. }
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(Scene.prototype, "debugLayer", {
  21899. // Properties
  21900. get: function () {
  21901. if (!this._debugLayer) {
  21902. this._debugLayer = new BABYLON.DebugLayer(this);
  21903. }
  21904. return this._debugLayer;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21910. get: function () {
  21911. return this._workerCollisions;
  21912. },
  21913. set: function (enabled) {
  21914. if (!BABYLON.CollisionCoordinatorLegacy) {
  21915. return;
  21916. }
  21917. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21918. this._workerCollisions = enabled;
  21919. if (this.collisionCoordinator) {
  21920. this.collisionCoordinator.destroy();
  21921. }
  21922. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21923. this.collisionCoordinator.init(this);
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21929. get: function () {
  21930. return this._selectionOctree;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21936. /**
  21937. * The mesh that is currently under the pointer.
  21938. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21939. */
  21940. get: function () {
  21941. return this._pointerOverMesh;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Scene.prototype, "pointerX", {
  21947. /**
  21948. * Current on-screen X position of the pointer
  21949. * @return {number} X position of the pointer
  21950. */
  21951. get: function () {
  21952. return this._pointerX;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. Object.defineProperty(Scene.prototype, "pointerY", {
  21958. /**
  21959. * Current on-screen Y position of the pointer
  21960. * @return {number} Y position of the pointer
  21961. */
  21962. get: function () {
  21963. return this._pointerY;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. Scene.prototype.getCachedMaterial = function () {
  21969. return this._cachedMaterial;
  21970. };
  21971. Scene.prototype.getCachedEffect = function () {
  21972. return this._cachedEffect;
  21973. };
  21974. Scene.prototype.getCachedVisibility = function () {
  21975. return this._cachedVisibility;
  21976. };
  21977. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21978. if (visibility === void 0) { visibility = 1; }
  21979. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21980. };
  21981. Scene.prototype.getBoundingBoxRenderer = function () {
  21982. if (!this._boundingBoxRenderer) {
  21983. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21984. }
  21985. return this._boundingBoxRenderer;
  21986. };
  21987. Scene.prototype.getOutlineRenderer = function () {
  21988. return this._outlineRenderer;
  21989. };
  21990. Scene.prototype.getEngine = function () {
  21991. return this._engine;
  21992. };
  21993. Scene.prototype.getTotalVertices = function () {
  21994. return this._totalVertices.current;
  21995. };
  21996. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21997. get: function () {
  21998. return this._totalVertices;
  21999. },
  22000. enumerable: true,
  22001. configurable: true
  22002. });
  22003. Scene.prototype.getActiveIndices = function () {
  22004. return this._activeIndices.current;
  22005. };
  22006. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22007. get: function () {
  22008. return this._activeIndices;
  22009. },
  22010. enumerable: true,
  22011. configurable: true
  22012. });
  22013. Scene.prototype.getActiveParticles = function () {
  22014. return this._activeParticles.current;
  22015. };
  22016. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22017. get: function () {
  22018. return this._activeParticles;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Scene.prototype.getActiveBones = function () {
  22024. return this._activeBones.current;
  22025. };
  22026. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22027. get: function () {
  22028. return this._activeBones;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. // Stats
  22034. Scene.prototype.getInterFramePerfCounter = function () {
  22035. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22036. return 0;
  22037. };
  22038. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22039. get: function () {
  22040. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22041. return null;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. Scene.prototype.getLastFrameDuration = function () {
  22047. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22048. return 0;
  22049. };
  22050. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22051. get: function () {
  22052. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22053. return null;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22059. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22060. return 0;
  22061. };
  22062. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22063. get: function () {
  22064. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22065. return null;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Scene.prototype.getActiveMeshes = function () {
  22071. return this._activeMeshes;
  22072. };
  22073. Scene.prototype.getRenderTargetsDuration = function () {
  22074. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22075. return 0;
  22076. };
  22077. Scene.prototype.getRenderDuration = function () {
  22078. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22079. return 0;
  22080. };
  22081. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22082. get: function () {
  22083. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22084. return null;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Scene.prototype.getParticlesDuration = function () {
  22090. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22091. return 0;
  22092. };
  22093. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22094. get: function () {
  22095. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22096. return null;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Scene.prototype.getSpritesDuration = function () {
  22102. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22103. return 0;
  22104. };
  22105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22106. get: function () {
  22107. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22108. return null;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Scene.prototype.getAnimationRatio = function () {
  22114. return this._animationRatio;
  22115. };
  22116. Scene.prototype.getRenderId = function () {
  22117. return this._renderId;
  22118. };
  22119. Scene.prototype.incrementRenderId = function () {
  22120. this._renderId++;
  22121. };
  22122. Scene.prototype._updatePointerPosition = function (evt) {
  22123. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22124. if (!canvasRect) {
  22125. return;
  22126. }
  22127. this._pointerX = evt.clientX - canvasRect.left;
  22128. this._pointerY = evt.clientY - canvasRect.top;
  22129. this._unTranslatedPointerX = this._pointerX;
  22130. this._unTranslatedPointerY = this._pointerY;
  22131. };
  22132. Scene.prototype._createUbo = function () {
  22133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22134. this._sceneUbo.addUniform("viewProjection", 16);
  22135. this._sceneUbo.addUniform("view", 16);
  22136. };
  22137. Scene.prototype._createAlternateUbo = function () {
  22138. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22139. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22140. this._alternateSceneUbo.addUniform("view", 16);
  22141. };
  22142. // Pointers handling
  22143. /**
  22144. * Use this method to simulate a pointer move on a mesh
  22145. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22146. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22147. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22148. */
  22149. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22150. var evt = new PointerEvent("pointermove", pointerEventInit);
  22151. return this._processPointerMove(pickResult, evt);
  22152. };
  22153. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22154. var canvas = this._engine.getRenderingCanvas();
  22155. if (!canvas) {
  22156. return this;
  22157. }
  22158. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22159. this.setPointerOverSprite(null);
  22160. this.setPointerOverMesh(pickResult.pickedMesh);
  22161. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22162. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22163. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22164. }
  22165. else {
  22166. canvas.style.cursor = this.hoverCursor;
  22167. }
  22168. }
  22169. else {
  22170. canvas.style.cursor = this.defaultCursor;
  22171. }
  22172. }
  22173. else {
  22174. this.setPointerOverMesh(null);
  22175. // Sprites
  22176. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22177. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22178. this.setPointerOverSprite(pickResult.pickedSprite);
  22179. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22180. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22181. }
  22182. else {
  22183. canvas.style.cursor = this.hoverCursor;
  22184. }
  22185. }
  22186. else {
  22187. this.setPointerOverSprite(null);
  22188. // Restore pointer
  22189. canvas.style.cursor = this.defaultCursor;
  22190. }
  22191. }
  22192. if (pickResult) {
  22193. if (this.onPointerMove) {
  22194. this.onPointerMove(evt, pickResult);
  22195. }
  22196. if (this.onPointerObservable.hasObservers()) {
  22197. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22198. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22199. this.onPointerObservable.notifyObservers(pi, type);
  22200. }
  22201. }
  22202. return this;
  22203. };
  22204. /**
  22205. * Use this method to simulate a pointer down on a mesh
  22206. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22207. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22208. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22209. */
  22210. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22211. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22212. return this._processPointerDown(pickResult, evt);
  22213. };
  22214. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22215. var _this = this;
  22216. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22217. this._pickedDownMesh = pickResult.pickedMesh;
  22218. var actionManager = pickResult.pickedMesh.actionManager;
  22219. if (actionManager) {
  22220. if (actionManager.hasPickTriggers) {
  22221. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22222. switch (evt.button) {
  22223. case 0:
  22224. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22225. break;
  22226. case 1:
  22227. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22228. break;
  22229. case 2:
  22230. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22231. break;
  22232. }
  22233. }
  22234. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22235. window.setTimeout(function () {
  22236. 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);
  22237. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22238. if (_this._totalPointersPressed !== 0 &&
  22239. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22240. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22241. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22242. _this._startingPointerTime = 0;
  22243. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22244. }
  22245. }
  22246. }, Scene.LongPressDelay);
  22247. }
  22248. }
  22249. }
  22250. if (pickResult) {
  22251. if (this.onPointerDown) {
  22252. this.onPointerDown(evt, pickResult);
  22253. }
  22254. if (this.onPointerObservable.hasObservers()) {
  22255. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22256. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22257. this.onPointerObservable.notifyObservers(pi, type);
  22258. }
  22259. }
  22260. return this;
  22261. };
  22262. /**
  22263. * Use this method to simulate a pointer up on a mesh
  22264. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22265. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22266. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22267. */
  22268. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22269. var evt = new PointerEvent("pointerup", pointerEventInit);
  22270. var clickInfo = new ClickInfo();
  22271. clickInfo.singleClick = true;
  22272. clickInfo.ignore = true;
  22273. return this._processPointerUp(pickResult, evt, clickInfo);
  22274. };
  22275. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22276. if (pickResult && pickResult && pickResult.pickedMesh) {
  22277. this._pickedUpMesh = pickResult.pickedMesh;
  22278. if (this._pickedDownMesh === this._pickedUpMesh) {
  22279. if (this.onPointerPick) {
  22280. this.onPointerPick(evt, pickResult);
  22281. }
  22282. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22283. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22284. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22285. this.onPointerObservable.notifyObservers(pi, type);
  22286. }
  22287. }
  22288. if (pickResult.pickedMesh.actionManager) {
  22289. if (clickInfo.ignore) {
  22290. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22291. }
  22292. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22293. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22294. }
  22295. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22296. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22297. }
  22298. }
  22299. }
  22300. if (this._pickedDownMesh &&
  22301. this._pickedDownMesh.actionManager &&
  22302. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22303. this._pickedDownMesh !== this._pickedUpMesh) {
  22304. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22305. }
  22306. if (this.onPointerUp) {
  22307. this.onPointerUp(evt, pickResult);
  22308. }
  22309. if (this.onPointerObservable.hasObservers()) {
  22310. if (!clickInfo.ignore) {
  22311. if (!clickInfo.hasSwiped) {
  22312. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22313. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22314. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22315. this.onPointerObservable.notifyObservers(pi, type);
  22316. }
  22317. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22318. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22319. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22320. this.onPointerObservable.notifyObservers(pi, type);
  22321. }
  22322. }
  22323. }
  22324. else {
  22325. var type = BABYLON.PointerEventTypes.POINTERUP;
  22326. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22327. this.onPointerObservable.notifyObservers(pi, type);
  22328. }
  22329. }
  22330. return this;
  22331. };
  22332. /**
  22333. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22334. * @param attachUp defines if you want to attach events to pointerup
  22335. * @param attachDown defines if you want to attach events to pointerdown
  22336. * @param attachMove defines if you want to attach events to pointermove
  22337. */
  22338. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22339. var _this = this;
  22340. if (attachUp === void 0) { attachUp = true; }
  22341. if (attachDown === void 0) { attachDown = true; }
  22342. if (attachMove === void 0) { attachMove = true; }
  22343. this._initActionManager = function (act, clickInfo) {
  22344. if (!_this._meshPickProceed) {
  22345. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22346. _this._currentPickResult = pickResult;
  22347. if (pickResult) {
  22348. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22349. }
  22350. _this._meshPickProceed = true;
  22351. }
  22352. return act;
  22353. };
  22354. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22355. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22356. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22357. btn !== _this._previousButtonPressed) {
  22358. _this._doubleClickOccured = false;
  22359. clickInfo.singleClick = true;
  22360. clickInfo.ignore = false;
  22361. cb(clickInfo, _this._currentPickResult);
  22362. }
  22363. };
  22364. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22365. var clickInfo = new ClickInfo();
  22366. _this._currentPickResult = null;
  22367. var act = null;
  22368. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22369. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22370. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22371. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22372. act = _this._initActionManager(act, clickInfo);
  22373. if (act)
  22374. checkPicking = act.hasPickTriggers;
  22375. }
  22376. if (checkPicking) {
  22377. var btn = evt.button;
  22378. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22379. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22380. if (!clickInfo.hasSwiped) {
  22381. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22382. if (!checkSingleClickImmediately) {
  22383. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22384. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22385. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22386. act = _this._initActionManager(act, clickInfo);
  22387. if (act)
  22388. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22389. }
  22390. }
  22391. if (checkSingleClickImmediately) {
  22392. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22393. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22394. btn !== _this._previousButtonPressed) {
  22395. clickInfo.singleClick = true;
  22396. cb(clickInfo, _this._currentPickResult);
  22397. }
  22398. }
  22399. else {
  22400. // wait that no double click has been raised during the double click delay
  22401. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22402. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22403. }
  22404. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22405. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22406. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22407. act = _this._initActionManager(act, clickInfo);
  22408. if (act)
  22409. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22410. }
  22411. if (checkDoubleClick) {
  22412. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22413. if (btn === _this._previousButtonPressed &&
  22414. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22415. !_this._doubleClickOccured) {
  22416. // pointer has not moved for 2 clicks, it's a double click
  22417. if (!clickInfo.hasSwiped &&
  22418. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22419. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22420. _this._previousStartingPointerTime = 0;
  22421. _this._doubleClickOccured = true;
  22422. clickInfo.doubleClick = true;
  22423. clickInfo.ignore = false;
  22424. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22425. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22426. }
  22427. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22428. cb(clickInfo, _this._currentPickResult);
  22429. }
  22430. else {
  22431. _this._doubleClickOccured = false;
  22432. _this._previousStartingPointerTime = _this._startingPointerTime;
  22433. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22434. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22435. _this._previousButtonPressed = btn;
  22436. if (Scene.ExclusiveDoubleClickMode) {
  22437. if (_this._previousDelayedSimpleClickTimeout) {
  22438. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22439. }
  22440. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22441. cb(clickInfo, _this._previousPickResult);
  22442. }
  22443. else {
  22444. cb(clickInfo, _this._currentPickResult);
  22445. }
  22446. }
  22447. }
  22448. else {
  22449. _this._doubleClickOccured = false;
  22450. _this._previousStartingPointerTime = _this._startingPointerTime;
  22451. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22452. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22453. _this._previousButtonPressed = btn;
  22454. }
  22455. }
  22456. }
  22457. }
  22458. clickInfo.ignore = true;
  22459. cb(clickInfo, _this._currentPickResult);
  22460. };
  22461. this._spritePredicate = function (sprite) {
  22462. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22463. };
  22464. this._onPointerMove = function (evt) {
  22465. _this._updatePointerPosition(evt);
  22466. // PreObservable support
  22467. if (_this.onPrePointerObservable.hasObservers()) {
  22468. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22469. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22470. _this.onPrePointerObservable.notifyObservers(pi, type);
  22471. if (pi.skipOnPointerObservable) {
  22472. return;
  22473. }
  22474. }
  22475. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22476. return;
  22477. }
  22478. if (!_this.pointerMovePredicate) {
  22479. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22480. }
  22481. // Meshes
  22482. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22483. _this._processPointerMove(pickResult, evt);
  22484. };
  22485. this._onPointerDown = function (evt) {
  22486. _this._totalPointersPressed++;
  22487. _this._pickedDownMesh = null;
  22488. _this._meshPickProceed = false;
  22489. _this._updatePointerPosition(evt);
  22490. if (_this.preventDefaultOnPointerDown && canvas) {
  22491. evt.preventDefault();
  22492. canvas.focus();
  22493. }
  22494. // PreObservable support
  22495. if (_this.onPrePointerObservable.hasObservers()) {
  22496. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22497. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22498. _this.onPrePointerObservable.notifyObservers(pi, type);
  22499. if (pi.skipOnPointerObservable) {
  22500. return;
  22501. }
  22502. }
  22503. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22504. return;
  22505. }
  22506. _this._startingPointerPosition.x = _this._pointerX;
  22507. _this._startingPointerPosition.y = _this._pointerY;
  22508. _this._startingPointerTime = new Date().getTime();
  22509. if (!_this.pointerDownPredicate) {
  22510. _this.pointerDownPredicate = function (mesh) {
  22511. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22512. };
  22513. }
  22514. // Meshes
  22515. _this._pickedDownMesh = null;
  22516. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22517. _this._processPointerDown(pickResult, evt);
  22518. // Sprites
  22519. _this._pickedDownSprite = null;
  22520. if (_this.spriteManagers.length > 0) {
  22521. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22522. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22523. if (pickResult.pickedSprite.actionManager) {
  22524. _this._pickedDownSprite = pickResult.pickedSprite;
  22525. switch (evt.button) {
  22526. case 0:
  22527. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22528. break;
  22529. case 1:
  22530. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22531. break;
  22532. case 2:
  22533. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22534. break;
  22535. }
  22536. if (pickResult.pickedSprite.actionManager) {
  22537. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22538. }
  22539. }
  22540. }
  22541. }
  22542. };
  22543. this._onPointerUp = function (evt) {
  22544. if (_this._totalPointersPressed === 0) {
  22545. return; // So we need to test it the pointer down was pressed before.
  22546. }
  22547. _this._totalPointersPressed--;
  22548. _this._pickedUpMesh = null;
  22549. _this._meshPickProceed = false;
  22550. _this._updatePointerPosition(evt);
  22551. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22552. // PreObservable support
  22553. if (_this.onPrePointerObservable.hasObservers()) {
  22554. if (!clickInfo.ignore) {
  22555. if (!clickInfo.hasSwiped) {
  22556. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22557. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22558. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22559. _this.onPrePointerObservable.notifyObservers(pi, type);
  22560. if (pi.skipOnPointerObservable) {
  22561. return;
  22562. }
  22563. }
  22564. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22565. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22566. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22567. _this.onPrePointerObservable.notifyObservers(pi, type);
  22568. if (pi.skipOnPointerObservable) {
  22569. return;
  22570. }
  22571. }
  22572. }
  22573. }
  22574. else {
  22575. var type = BABYLON.PointerEventTypes.POINTERUP;
  22576. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22577. _this.onPrePointerObservable.notifyObservers(pi, type);
  22578. if (pi.skipOnPointerObservable) {
  22579. return;
  22580. }
  22581. }
  22582. }
  22583. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22584. return;
  22585. }
  22586. if (!_this.pointerUpPredicate) {
  22587. _this.pointerUpPredicate = function (mesh) {
  22588. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22589. };
  22590. }
  22591. // Meshes
  22592. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22593. _this._initActionManager(null, clickInfo);
  22594. }
  22595. if (!pickResult) {
  22596. pickResult = _this._currentPickResult;
  22597. }
  22598. _this._processPointerUp(pickResult, evt, clickInfo);
  22599. // Sprites
  22600. if (_this.spriteManagers.length > 0) {
  22601. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22602. if (spritePickResult) {
  22603. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22604. if (spritePickResult.pickedSprite.actionManager) {
  22605. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22606. if (spritePickResult.pickedSprite.actionManager) {
  22607. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22608. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22609. }
  22610. }
  22611. }
  22612. }
  22613. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22614. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22615. }
  22616. }
  22617. }
  22618. _this._previousPickResult = _this._currentPickResult;
  22619. });
  22620. };
  22621. this._onKeyDown = function (evt) {
  22622. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22623. if (_this.onPreKeyboardObservable.hasObservers()) {
  22624. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22625. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22626. if (pi.skipOnPointerObservable) {
  22627. return;
  22628. }
  22629. }
  22630. if (_this.onKeyboardObservable.hasObservers()) {
  22631. var pi = new BABYLON.KeyboardInfo(type, evt);
  22632. _this.onKeyboardObservable.notifyObservers(pi, type);
  22633. }
  22634. if (_this.actionManager) {
  22635. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22636. }
  22637. };
  22638. this._onKeyUp = function (evt) {
  22639. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22640. if (_this.onPreKeyboardObservable.hasObservers()) {
  22641. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22642. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22643. if (pi.skipOnPointerObservable) {
  22644. return;
  22645. }
  22646. }
  22647. if (_this.onKeyboardObservable.hasObservers()) {
  22648. var pi = new BABYLON.KeyboardInfo(type, evt);
  22649. _this.onKeyboardObservable.notifyObservers(pi, type);
  22650. }
  22651. if (_this.actionManager) {
  22652. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22653. }
  22654. };
  22655. var engine = this.getEngine();
  22656. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22657. if (!canvas) {
  22658. return;
  22659. }
  22660. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22661. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22662. });
  22663. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22664. if (!canvas) {
  22665. return;
  22666. }
  22667. canvas.removeEventListener("keydown", _this._onKeyDown);
  22668. canvas.removeEventListener("keyup", _this._onKeyUp);
  22669. });
  22670. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22671. var canvas = this._engine.getRenderingCanvas();
  22672. if (!canvas) {
  22673. return;
  22674. }
  22675. if (attachMove) {
  22676. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22677. // Wheel
  22678. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22679. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22680. }
  22681. if (attachDown) {
  22682. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22683. }
  22684. if (attachUp) {
  22685. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22686. }
  22687. canvas.tabIndex = 1;
  22688. };
  22689. Scene.prototype.detachControl = function () {
  22690. var engine = this.getEngine();
  22691. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22692. var canvas = engine.getRenderingCanvas();
  22693. if (!canvas) {
  22694. return;
  22695. }
  22696. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22697. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22698. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22699. if (this._onCanvasBlurObserver) {
  22700. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22701. }
  22702. if (this._onCanvasFocusObserver) {
  22703. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22704. }
  22705. // Wheel
  22706. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22707. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22708. // Keyboard
  22709. canvas.removeEventListener("keydown", this._onKeyDown);
  22710. canvas.removeEventListener("keyup", this._onKeyUp);
  22711. // Observables
  22712. this.onKeyboardObservable.clear();
  22713. this.onPreKeyboardObservable.clear();
  22714. this.onPointerObservable.clear();
  22715. this.onPrePointerObservable.clear();
  22716. };
  22717. /**
  22718. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22719. * Delay loaded resources are not taking in account
  22720. * @return true if all required resources are ready
  22721. */
  22722. Scene.prototype.isReady = function () {
  22723. if (this._isDisposed) {
  22724. return false;
  22725. }
  22726. if (this._pendingData.length > 0) {
  22727. return false;
  22728. }
  22729. var index;
  22730. var engine = this.getEngine();
  22731. // Geometries
  22732. for (index = 0; index < this._geometries.length; index++) {
  22733. var geometry = this._geometries[index];
  22734. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22735. return false;
  22736. }
  22737. }
  22738. // Meshes
  22739. for (index = 0; index < this.meshes.length; index++) {
  22740. var mesh = this.meshes[index];
  22741. if (!mesh.isEnabled()) {
  22742. continue;
  22743. }
  22744. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22745. continue;
  22746. }
  22747. if (!mesh.isReady(true)) {
  22748. return false;
  22749. }
  22750. // Effect layers
  22751. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22752. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22753. var layer = _a[_i];
  22754. if (!layer.hasMesh(mesh)) {
  22755. continue;
  22756. }
  22757. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22758. var subMesh = _c[_b];
  22759. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22760. return false;
  22761. }
  22762. }
  22763. }
  22764. }
  22765. return true;
  22766. };
  22767. Scene.prototype.resetCachedMaterial = function () {
  22768. this._cachedMaterial = null;
  22769. this._cachedEffect = null;
  22770. this._cachedVisibility = null;
  22771. };
  22772. Scene.prototype.registerBeforeRender = function (func) {
  22773. this.onBeforeRenderObservable.add(func);
  22774. };
  22775. Scene.prototype.unregisterBeforeRender = function (func) {
  22776. this.onBeforeRenderObservable.removeCallback(func);
  22777. };
  22778. Scene.prototype.registerAfterRender = function (func) {
  22779. this.onAfterRenderObservable.add(func);
  22780. };
  22781. Scene.prototype.unregisterAfterRender = function (func) {
  22782. this.onAfterRenderObservable.removeCallback(func);
  22783. };
  22784. Scene.prototype._executeOnceBeforeRender = function (func) {
  22785. var _this = this;
  22786. var execFunc = function () {
  22787. func();
  22788. setTimeout(function () {
  22789. _this.unregisterBeforeRender(execFunc);
  22790. });
  22791. };
  22792. this.registerBeforeRender(execFunc);
  22793. };
  22794. /**
  22795. * The provided function will run before render once and will be disposed afterwards.
  22796. * A timeout delay can be provided so that the function will be executed in N ms.
  22797. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22798. * @param func The function to be executed.
  22799. * @param timeout optional delay in ms
  22800. */
  22801. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22802. var _this = this;
  22803. if (timeout !== undefined) {
  22804. setTimeout(function () {
  22805. _this._executeOnceBeforeRender(func);
  22806. }, timeout);
  22807. }
  22808. else {
  22809. this._executeOnceBeforeRender(func);
  22810. }
  22811. };
  22812. Scene.prototype._addPendingData = function (data) {
  22813. this._pendingData.push(data);
  22814. };
  22815. Scene.prototype._removePendingData = function (data) {
  22816. var wasLoading = this.isLoading;
  22817. var index = this._pendingData.indexOf(data);
  22818. if (index !== -1) {
  22819. this._pendingData.splice(index, 1);
  22820. }
  22821. if (wasLoading && !this.isLoading) {
  22822. this.onDataLoadedObservable.notifyObservers(this);
  22823. }
  22824. };
  22825. Scene.prototype.getWaitingItemsCount = function () {
  22826. return this._pendingData.length;
  22827. };
  22828. Object.defineProperty(Scene.prototype, "isLoading", {
  22829. get: function () {
  22830. return this._pendingData.length > 0;
  22831. },
  22832. enumerable: true,
  22833. configurable: true
  22834. });
  22835. /**
  22836. * Registers a function to be executed when the scene is ready.
  22837. * @param {Function} func - the function to be executed.
  22838. */
  22839. Scene.prototype.executeWhenReady = function (func) {
  22840. var _this = this;
  22841. this.onReadyObservable.add(func);
  22842. if (this._executeWhenReadyTimeoutId !== -1) {
  22843. return;
  22844. }
  22845. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22846. _this._checkIsReady();
  22847. }, 150);
  22848. };
  22849. /**
  22850. * Returns a promise that resolves when the scene is ready.
  22851. * @returns A promise that resolves when the scene is ready.
  22852. */
  22853. Scene.prototype.whenReadyAsync = function () {
  22854. var _this = this;
  22855. return new Promise(function (resolve) {
  22856. _this.executeWhenReady(function () {
  22857. resolve();
  22858. });
  22859. });
  22860. };
  22861. Scene.prototype._checkIsReady = function () {
  22862. var _this = this;
  22863. if (this.isReady()) {
  22864. this.onReadyObservable.notifyObservers(this);
  22865. this.onReadyObservable.clear();
  22866. this._executeWhenReadyTimeoutId = -1;
  22867. return;
  22868. }
  22869. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22870. _this._checkIsReady();
  22871. }, 150);
  22872. };
  22873. // Animations
  22874. /**
  22875. * Will start the animation sequence of a given target
  22876. * @param target - the target
  22877. * @param {number} from - from which frame should animation start
  22878. * @param {number} to - till which frame should animation run.
  22879. * @param {boolean} [loop] - should the animation loop
  22880. * @param {number} [speedRatio] - the speed in which to run the animation
  22881. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22882. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22883. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22884. * See BABYLON.Animatable
  22885. */
  22886. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22887. if (speedRatio === void 0) { speedRatio = 1.0; }
  22888. if (from > to && speedRatio > 0) {
  22889. speedRatio *= -1;
  22890. }
  22891. this.stopAnimation(target);
  22892. if (!animatable) {
  22893. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22894. }
  22895. // Local animations
  22896. if (target.animations) {
  22897. animatable.appendAnimations(target, target.animations);
  22898. }
  22899. // Children animations
  22900. if (target.getAnimatables) {
  22901. var animatables = target.getAnimatables();
  22902. for (var index = 0; index < animatables.length; index++) {
  22903. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22904. }
  22905. }
  22906. animatable.reset();
  22907. return animatable;
  22908. };
  22909. /**
  22910. * Begin a new animation on a given node
  22911. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22912. * @param {BABYLON.Animation[]} defines the list of animations to start
  22913. * @param {number} from defines the initial value
  22914. * @param {number} to defines the final value
  22915. * @param {boolean} loop defines if you want animation to loop (off by default)
  22916. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22917. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22918. * @returns the list of created animatables
  22919. */
  22920. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22921. if (speedRatio === undefined) {
  22922. speedRatio = 1.0;
  22923. }
  22924. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22925. return animatable;
  22926. };
  22927. /**
  22928. * Begin a new animation on a given node and its hierarchy
  22929. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22930. * @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.
  22931. * @param {BABYLON.Animation[]} defines the list of animations to start
  22932. * @param {number} from defines the initial value
  22933. * @param {number} to defines the final value
  22934. * @param {boolean} loop defines if you want animation to loop (off by default)
  22935. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22936. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22937. * @returns the list of animatables created for all nodes
  22938. */
  22939. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22940. var children = target.getDescendants(directDescendantsOnly);
  22941. var result = [];
  22942. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22943. var child = children_1[_i];
  22944. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22945. }
  22946. return result;
  22947. };
  22948. Scene.prototype.getAnimatableByTarget = function (target) {
  22949. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22950. if (this._activeAnimatables[index].target === target) {
  22951. return this._activeAnimatables[index];
  22952. }
  22953. }
  22954. return null;
  22955. };
  22956. Object.defineProperty(Scene.prototype, "animatables", {
  22957. get: function () {
  22958. return this._activeAnimatables;
  22959. },
  22960. enumerable: true,
  22961. configurable: true
  22962. });
  22963. /**
  22964. * Will stop the animation of the given target
  22965. * @param target - the target
  22966. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22967. * @see beginAnimation
  22968. */
  22969. Scene.prototype.stopAnimation = function (target, animationName) {
  22970. var animatable = this.getAnimatableByTarget(target);
  22971. if (animatable) {
  22972. animatable.stop(animationName);
  22973. }
  22974. };
  22975. /**
  22976. * Stops and removes all animations that have been applied to the scene
  22977. */
  22978. Scene.prototype.stopAllAnimations = function () {
  22979. if (this._activeAnimatables) {
  22980. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22981. this._activeAnimatables[i].stop();
  22982. }
  22983. this._activeAnimatables = [];
  22984. }
  22985. };
  22986. Scene.prototype._animate = function () {
  22987. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22988. return;
  22989. }
  22990. // Getting time
  22991. var now = BABYLON.Tools.Now;
  22992. if (!this._animationTimeLast) {
  22993. if (this._pendingData.length > 0) {
  22994. return;
  22995. }
  22996. this._animationTimeLast = now;
  22997. }
  22998. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22999. this._animationTime += deltaTime;
  23000. this._animationTimeLast = now;
  23001. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23002. this._activeAnimatables[index]._animate(this._animationTime);
  23003. }
  23004. };
  23005. // Matrix
  23006. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23007. this._useAlternateCameraConfiguration = active;
  23008. };
  23009. Scene.prototype.getViewMatrix = function () {
  23010. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23011. };
  23012. Scene.prototype.getProjectionMatrix = function () {
  23013. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23014. };
  23015. Scene.prototype.getTransformMatrix = function () {
  23016. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23017. };
  23018. Scene.prototype.setTransformMatrix = function (view, projection) {
  23019. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23020. return;
  23021. }
  23022. this._viewUpdateFlag = view.updateFlag;
  23023. this._projectionUpdateFlag = projection.updateFlag;
  23024. this._viewMatrix = view;
  23025. this._projectionMatrix = projection;
  23026. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23027. // Update frustum
  23028. if (!this._frustumPlanes) {
  23029. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23030. }
  23031. else {
  23032. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23033. }
  23034. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23035. var otherCamera = this.activeCamera._alternateCamera;
  23036. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23037. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23038. }
  23039. if (this._sceneUbo.useUbo) {
  23040. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23041. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23042. this._sceneUbo.update();
  23043. }
  23044. };
  23045. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23046. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23047. return;
  23048. }
  23049. this._alternateViewUpdateFlag = view.updateFlag;
  23050. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23051. this._alternateViewMatrix = view;
  23052. this._alternateProjectionMatrix = projection;
  23053. if (!this._alternateTransformMatrix) {
  23054. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23055. }
  23056. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23057. if (!this._alternateSceneUbo) {
  23058. this._createAlternateUbo();
  23059. }
  23060. if (this._alternateSceneUbo.useUbo) {
  23061. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23062. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23063. this._alternateSceneUbo.update();
  23064. }
  23065. };
  23066. Scene.prototype.getSceneUniformBuffer = function () {
  23067. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23068. };
  23069. // Methods
  23070. Scene.prototype.getUniqueId = function () {
  23071. var result = Scene._uniqueIdCounter;
  23072. Scene._uniqueIdCounter++;
  23073. return result;
  23074. };
  23075. Scene.prototype.addMesh = function (newMesh) {
  23076. this.meshes.push(newMesh);
  23077. //notify the collision coordinator
  23078. if (this.collisionCoordinator) {
  23079. this.collisionCoordinator.onMeshAdded(newMesh);
  23080. }
  23081. newMesh._resyncLightSources();
  23082. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23083. };
  23084. Scene.prototype.removeMesh = function (toRemove) {
  23085. var index = this.meshes.indexOf(toRemove);
  23086. if (index !== -1) {
  23087. // Remove from the scene if mesh found
  23088. this.meshes.splice(index, 1);
  23089. }
  23090. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23091. return index;
  23092. };
  23093. Scene.prototype.addTransformNode = function (newTransformNode) {
  23094. this.transformNodes.push(newTransformNode);
  23095. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23096. };
  23097. Scene.prototype.removeTransformNode = function (toRemove) {
  23098. var index = this.transformNodes.indexOf(toRemove);
  23099. if (index !== -1) {
  23100. // Remove from the scene if found
  23101. this.transformNodes.splice(index, 1);
  23102. }
  23103. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23104. return index;
  23105. };
  23106. Scene.prototype.removeSkeleton = function (toRemove) {
  23107. var index = this.skeletons.indexOf(toRemove);
  23108. if (index !== -1) {
  23109. // Remove from the scene if found
  23110. this.skeletons.splice(index, 1);
  23111. }
  23112. return index;
  23113. };
  23114. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23115. var index = this.morphTargetManagers.indexOf(toRemove);
  23116. if (index !== -1) {
  23117. // Remove from the scene if found
  23118. this.morphTargetManagers.splice(index, 1);
  23119. }
  23120. return index;
  23121. };
  23122. Scene.prototype.removeLight = function (toRemove) {
  23123. var index = this.lights.indexOf(toRemove);
  23124. if (index !== -1) {
  23125. // Remove from meshes
  23126. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23127. var mesh = _a[_i];
  23128. mesh._removeLightSource(toRemove);
  23129. }
  23130. // Remove from the scene if mesh found
  23131. this.lights.splice(index, 1);
  23132. this.sortLightsByPriority();
  23133. }
  23134. this.onLightRemovedObservable.notifyObservers(toRemove);
  23135. return index;
  23136. };
  23137. Scene.prototype.removeCamera = function (toRemove) {
  23138. var index = this.cameras.indexOf(toRemove);
  23139. if (index !== -1) {
  23140. // Remove from the scene if mesh found
  23141. this.cameras.splice(index, 1);
  23142. }
  23143. // Remove from activeCameras
  23144. var index2 = this.activeCameras.indexOf(toRemove);
  23145. if (index2 !== -1) {
  23146. // Remove from the scene if mesh found
  23147. this.activeCameras.splice(index2, 1);
  23148. }
  23149. // Reset the activeCamera
  23150. if (this.activeCamera === toRemove) {
  23151. if (this.cameras.length > 0) {
  23152. this.activeCamera = this.cameras[0];
  23153. }
  23154. else {
  23155. this.activeCamera = null;
  23156. }
  23157. }
  23158. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23159. return index;
  23160. };
  23161. Scene.prototype.removeParticleSystem = function (toRemove) {
  23162. var index = this.particleSystems.indexOf(toRemove);
  23163. if (index !== -1) {
  23164. this.particleSystems.splice(index, 1);
  23165. }
  23166. return index;
  23167. };
  23168. ;
  23169. Scene.prototype.removeAnimation = function (toRemove) {
  23170. var index = this.animations.indexOf(toRemove);
  23171. if (index !== -1) {
  23172. this.animations.splice(index, 1);
  23173. }
  23174. return index;
  23175. };
  23176. ;
  23177. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23178. var index = this.multiMaterials.indexOf(toRemove);
  23179. if (index !== -1) {
  23180. this.multiMaterials.splice(index, 1);
  23181. }
  23182. return index;
  23183. };
  23184. ;
  23185. Scene.prototype.removeMaterial = function (toRemove) {
  23186. var index = this.materials.indexOf(toRemove);
  23187. if (index !== -1) {
  23188. this.materials.splice(index, 1);
  23189. }
  23190. return index;
  23191. };
  23192. ;
  23193. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23194. var index = this.lensFlareSystems.indexOf(toRemove);
  23195. if (index !== -1) {
  23196. this.lensFlareSystems.splice(index, 1);
  23197. }
  23198. return index;
  23199. };
  23200. ;
  23201. Scene.prototype.removeActionManager = function (toRemove) {
  23202. var index = this._actionManagers.indexOf(toRemove);
  23203. if (index !== -1) {
  23204. this._actionManagers.splice(index, 1);
  23205. }
  23206. return index;
  23207. };
  23208. ;
  23209. Scene.prototype.addLight = function (newLight) {
  23210. this.lights.push(newLight);
  23211. this.sortLightsByPriority();
  23212. // Add light to all meshes (To support if the light is removed and then readded)
  23213. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23214. var mesh = _a[_i];
  23215. if (mesh._lightSources.indexOf(newLight) === -1) {
  23216. mesh._lightSources.push(newLight);
  23217. mesh._resyncLightSources();
  23218. }
  23219. }
  23220. this.onNewLightAddedObservable.notifyObservers(newLight);
  23221. };
  23222. Scene.prototype.sortLightsByPriority = function () {
  23223. if (this.requireLightSorting) {
  23224. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23225. }
  23226. };
  23227. Scene.prototype.addCamera = function (newCamera) {
  23228. this.cameras.push(newCamera);
  23229. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23230. };
  23231. Scene.prototype.addSkeleton = function (newSkeleton) {
  23232. this.skeletons.push(newSkeleton);
  23233. };
  23234. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23235. this.particleSystems.push(newParticleSystem);
  23236. };
  23237. Scene.prototype.addAnimation = function (newAnimation) {
  23238. this.animations.push(newAnimation);
  23239. };
  23240. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23241. this.multiMaterials.push(newMultiMaterial);
  23242. };
  23243. Scene.prototype.addMaterial = function (newMaterial) {
  23244. this.materials.push(newMaterial);
  23245. };
  23246. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23247. this.morphTargetManagers.push(newMorphTargetManager);
  23248. };
  23249. Scene.prototype.addGeometry = function (newGeometrie) {
  23250. this._geometries.push(newGeometrie);
  23251. };
  23252. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23253. this.lensFlareSystems.push(newLensFlareSystem);
  23254. };
  23255. Scene.prototype.addActionManager = function (newActionManager) {
  23256. this._actionManagers.push(newActionManager);
  23257. };
  23258. /**
  23259. * Switch active camera
  23260. * @param {Camera} newCamera - new active camera
  23261. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23262. */
  23263. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23264. if (attachControl === void 0) { attachControl = true; }
  23265. var canvas = this._engine.getRenderingCanvas();
  23266. if (!canvas) {
  23267. return;
  23268. }
  23269. if (this.activeCamera) {
  23270. this.activeCamera.detachControl(canvas);
  23271. }
  23272. this.activeCamera = newCamera;
  23273. if (attachControl) {
  23274. newCamera.attachControl(canvas);
  23275. }
  23276. };
  23277. /**
  23278. * sets the active camera of the scene using its ID
  23279. * @param {string} id - the camera's ID
  23280. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23281. * @see activeCamera
  23282. */
  23283. Scene.prototype.setActiveCameraByID = function (id) {
  23284. var camera = this.getCameraByID(id);
  23285. if (camera) {
  23286. this.activeCamera = camera;
  23287. return camera;
  23288. }
  23289. return null;
  23290. };
  23291. /**
  23292. * sets the active camera of the scene using its name
  23293. * @param {string} name - the camera's name
  23294. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23295. * @see activeCamera
  23296. */
  23297. Scene.prototype.setActiveCameraByName = function (name) {
  23298. var camera = this.getCameraByName(name);
  23299. if (camera) {
  23300. this.activeCamera = camera;
  23301. return camera;
  23302. }
  23303. return null;
  23304. };
  23305. /**
  23306. * get an animation group using its name
  23307. * @param {string} the material's name
  23308. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23309. */
  23310. Scene.prototype.getAnimationGroupByName = function (name) {
  23311. for (var index = 0; index < this.animationGroups.length; index++) {
  23312. if (this.animationGroups[index].name === name) {
  23313. return this.animationGroups[index];
  23314. }
  23315. }
  23316. return null;
  23317. };
  23318. /**
  23319. * get a material using its id
  23320. * @param {string} the material's ID
  23321. * @return {BABYLON.Material|null} the material or null if none found.
  23322. */
  23323. Scene.prototype.getMaterialByID = function (id) {
  23324. for (var index = 0; index < this.materials.length; index++) {
  23325. if (this.materials[index].id === id) {
  23326. return this.materials[index];
  23327. }
  23328. }
  23329. return null;
  23330. };
  23331. /**
  23332. * get a material using its name
  23333. * @param {string} the material's name
  23334. * @return {BABYLON.Material|null} the material or null if none found.
  23335. */
  23336. Scene.prototype.getMaterialByName = function (name) {
  23337. for (var index = 0; index < this.materials.length; index++) {
  23338. if (this.materials[index].name === name) {
  23339. return this.materials[index];
  23340. }
  23341. }
  23342. return null;
  23343. };
  23344. Scene.prototype.getLensFlareSystemByName = function (name) {
  23345. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23346. if (this.lensFlareSystems[index].name === name) {
  23347. return this.lensFlareSystems[index];
  23348. }
  23349. }
  23350. return null;
  23351. };
  23352. Scene.prototype.getLensFlareSystemByID = function (id) {
  23353. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23354. if (this.lensFlareSystems[index].id === id) {
  23355. return this.lensFlareSystems[index];
  23356. }
  23357. }
  23358. return null;
  23359. };
  23360. Scene.prototype.getCameraByID = function (id) {
  23361. for (var index = 0; index < this.cameras.length; index++) {
  23362. if (this.cameras[index].id === id) {
  23363. return this.cameras[index];
  23364. }
  23365. }
  23366. return null;
  23367. };
  23368. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23369. for (var index = 0; index < this.cameras.length; index++) {
  23370. if (this.cameras[index].uniqueId === uniqueId) {
  23371. return this.cameras[index];
  23372. }
  23373. }
  23374. return null;
  23375. };
  23376. /**
  23377. * get a camera using its name
  23378. * @param {string} the camera's name
  23379. * @return {BABYLON.Camera|null} the camera or null if none found.
  23380. */
  23381. Scene.prototype.getCameraByName = function (name) {
  23382. for (var index = 0; index < this.cameras.length; index++) {
  23383. if (this.cameras[index].name === name) {
  23384. return this.cameras[index];
  23385. }
  23386. }
  23387. return null;
  23388. };
  23389. /**
  23390. * get a bone using its id
  23391. * @param {string} the bone's id
  23392. * @return {BABYLON.Bone|null} the bone or null if not found
  23393. */
  23394. Scene.prototype.getBoneByID = function (id) {
  23395. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23396. var skeleton = this.skeletons[skeletonIndex];
  23397. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23398. if (skeleton.bones[boneIndex].id === id) {
  23399. return skeleton.bones[boneIndex];
  23400. }
  23401. }
  23402. }
  23403. return null;
  23404. };
  23405. /**
  23406. * get a bone using its id
  23407. * @param {string} the bone's name
  23408. * @return {BABYLON.Bone|null} the bone or null if not found
  23409. */
  23410. Scene.prototype.getBoneByName = function (name) {
  23411. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23412. var skeleton = this.skeletons[skeletonIndex];
  23413. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23414. if (skeleton.bones[boneIndex].name === name) {
  23415. return skeleton.bones[boneIndex];
  23416. }
  23417. }
  23418. }
  23419. return null;
  23420. };
  23421. /**
  23422. * get a light node using its name
  23423. * @param {string} the light's name
  23424. * @return {BABYLON.Light|null} the light or null if none found.
  23425. */
  23426. Scene.prototype.getLightByName = function (name) {
  23427. for (var index = 0; index < this.lights.length; index++) {
  23428. if (this.lights[index].name === name) {
  23429. return this.lights[index];
  23430. }
  23431. }
  23432. return null;
  23433. };
  23434. /**
  23435. * get a light node using its ID
  23436. * @param {string} the light's id
  23437. * @return {BABYLON.Light|null} the light or null if none found.
  23438. */
  23439. Scene.prototype.getLightByID = function (id) {
  23440. for (var index = 0; index < this.lights.length; index++) {
  23441. if (this.lights[index].id === id) {
  23442. return this.lights[index];
  23443. }
  23444. }
  23445. return null;
  23446. };
  23447. /**
  23448. * get a light node using its scene-generated unique ID
  23449. * @param {number} the light's unique id
  23450. * @return {BABYLON.Light|null} the light or null if none found.
  23451. */
  23452. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23453. for (var index = 0; index < this.lights.length; index++) {
  23454. if (this.lights[index].uniqueId === uniqueId) {
  23455. return this.lights[index];
  23456. }
  23457. }
  23458. return null;
  23459. };
  23460. /**
  23461. * get a particle system by id
  23462. * @param id {number} the particle system id
  23463. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23464. */
  23465. Scene.prototype.getParticleSystemByID = function (id) {
  23466. for (var index = 0; index < this.particleSystems.length; index++) {
  23467. if (this.particleSystems[index].id === id) {
  23468. return this.particleSystems[index];
  23469. }
  23470. }
  23471. return null;
  23472. };
  23473. /**
  23474. * get a geometry using its ID
  23475. * @param {string} the geometry's id
  23476. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23477. */
  23478. Scene.prototype.getGeometryByID = function (id) {
  23479. for (var index = 0; index < this._geometries.length; index++) {
  23480. if (this._geometries[index].id === id) {
  23481. return this._geometries[index];
  23482. }
  23483. }
  23484. return null;
  23485. };
  23486. /**
  23487. * add a new geometry to this scene.
  23488. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23489. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23490. * @return {boolean} was the geometry added or not
  23491. */
  23492. Scene.prototype.pushGeometry = function (geometry, force) {
  23493. if (!force && this.getGeometryByID(geometry.id)) {
  23494. return false;
  23495. }
  23496. this._geometries.push(geometry);
  23497. //notify the collision coordinator
  23498. if (this.collisionCoordinator) {
  23499. this.collisionCoordinator.onGeometryAdded(geometry);
  23500. }
  23501. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23502. return true;
  23503. };
  23504. /**
  23505. * Removes an existing geometry
  23506. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23507. * @return {boolean} was the geometry removed or not
  23508. */
  23509. Scene.prototype.removeGeometry = function (geometry) {
  23510. var index = this._geometries.indexOf(geometry);
  23511. if (index > -1) {
  23512. this._geometries.splice(index, 1);
  23513. //notify the collision coordinator
  23514. if (this.collisionCoordinator) {
  23515. this.collisionCoordinator.onGeometryDeleted(geometry);
  23516. }
  23517. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23518. return true;
  23519. }
  23520. return false;
  23521. };
  23522. Scene.prototype.getGeometries = function () {
  23523. return this._geometries;
  23524. };
  23525. /**
  23526. * Get the first added mesh found of a given ID
  23527. * @param {string} id - the id to search for
  23528. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23529. */
  23530. Scene.prototype.getMeshByID = function (id) {
  23531. for (var index = 0; index < this.meshes.length; index++) {
  23532. if (this.meshes[index].id === id) {
  23533. return this.meshes[index];
  23534. }
  23535. }
  23536. return null;
  23537. };
  23538. Scene.prototype.getMeshesByID = function (id) {
  23539. return this.meshes.filter(function (m) {
  23540. return m.id === id;
  23541. });
  23542. };
  23543. /**
  23544. * Get the first added transform node found of a given ID
  23545. * @param {string} id - the id to search for
  23546. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23547. */
  23548. Scene.prototype.getTransformNodeByID = function (id) {
  23549. for (var index = 0; index < this.transformNodes.length; index++) {
  23550. if (this.transformNodes[index].id === id) {
  23551. return this.transformNodes[index];
  23552. }
  23553. }
  23554. return null;
  23555. };
  23556. Scene.prototype.getTransformNodesByID = function (id) {
  23557. return this.transformNodes.filter(function (m) {
  23558. return m.id === id;
  23559. });
  23560. };
  23561. /**
  23562. * Get a mesh with its auto-generated unique id
  23563. * @param {number} uniqueId - the unique id to search for
  23564. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23565. */
  23566. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23567. for (var index = 0; index < this.meshes.length; index++) {
  23568. if (this.meshes[index].uniqueId === uniqueId) {
  23569. return this.meshes[index];
  23570. }
  23571. }
  23572. return null;
  23573. };
  23574. /**
  23575. * Get a the last added mesh found of a given ID
  23576. * @param {string} id - the id to search for
  23577. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23578. */
  23579. Scene.prototype.getLastMeshByID = function (id) {
  23580. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23581. if (this.meshes[index].id === id) {
  23582. return this.meshes[index];
  23583. }
  23584. }
  23585. return null;
  23586. };
  23587. /**
  23588. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23589. * @param {string} id - the id to search for
  23590. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23591. */
  23592. Scene.prototype.getLastEntryByID = function (id) {
  23593. var index;
  23594. for (index = this.meshes.length - 1; index >= 0; index--) {
  23595. if (this.meshes[index].id === id) {
  23596. return this.meshes[index];
  23597. }
  23598. }
  23599. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23600. if (this.transformNodes[index].id === id) {
  23601. return this.transformNodes[index];
  23602. }
  23603. }
  23604. for (index = this.cameras.length - 1; index >= 0; index--) {
  23605. if (this.cameras[index].id === id) {
  23606. return this.cameras[index];
  23607. }
  23608. }
  23609. for (index = this.lights.length - 1; index >= 0; index--) {
  23610. if (this.lights[index].id === id) {
  23611. return this.lights[index];
  23612. }
  23613. }
  23614. return null;
  23615. };
  23616. Scene.prototype.getNodeByID = function (id) {
  23617. var mesh = this.getMeshByID(id);
  23618. if (mesh) {
  23619. return mesh;
  23620. }
  23621. var light = this.getLightByID(id);
  23622. if (light) {
  23623. return light;
  23624. }
  23625. var camera = this.getCameraByID(id);
  23626. if (camera) {
  23627. return camera;
  23628. }
  23629. var bone = this.getBoneByID(id);
  23630. return bone;
  23631. };
  23632. Scene.prototype.getNodeByName = function (name) {
  23633. var mesh = this.getMeshByName(name);
  23634. if (mesh) {
  23635. return mesh;
  23636. }
  23637. var light = this.getLightByName(name);
  23638. if (light) {
  23639. return light;
  23640. }
  23641. var camera = this.getCameraByName(name);
  23642. if (camera) {
  23643. return camera;
  23644. }
  23645. var bone = this.getBoneByName(name);
  23646. return bone;
  23647. };
  23648. Scene.prototype.getMeshByName = function (name) {
  23649. for (var index = 0; index < this.meshes.length; index++) {
  23650. if (this.meshes[index].name === name) {
  23651. return this.meshes[index];
  23652. }
  23653. }
  23654. return null;
  23655. };
  23656. Scene.prototype.getTransformNodeByName = function (name) {
  23657. for (var index = 0; index < this.transformNodes.length; index++) {
  23658. if (this.transformNodes[index].name === name) {
  23659. return this.transformNodes[index];
  23660. }
  23661. }
  23662. return null;
  23663. };
  23664. Scene.prototype.getSoundByName = function (name) {
  23665. var index;
  23666. if (BABYLON.AudioEngine) {
  23667. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23668. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23669. return this.mainSoundTrack.soundCollection[index];
  23670. }
  23671. }
  23672. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23673. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23674. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23675. return this.soundTracks[sdIndex].soundCollection[index];
  23676. }
  23677. }
  23678. }
  23679. }
  23680. return null;
  23681. };
  23682. Scene.prototype.getLastSkeletonByID = function (id) {
  23683. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23684. if (this.skeletons[index].id === id) {
  23685. return this.skeletons[index];
  23686. }
  23687. }
  23688. return null;
  23689. };
  23690. Scene.prototype.getSkeletonById = function (id) {
  23691. for (var index = 0; index < this.skeletons.length; index++) {
  23692. if (this.skeletons[index].id === id) {
  23693. return this.skeletons[index];
  23694. }
  23695. }
  23696. return null;
  23697. };
  23698. Scene.prototype.getSkeletonByName = function (name) {
  23699. for (var index = 0; index < this.skeletons.length; index++) {
  23700. if (this.skeletons[index].name === name) {
  23701. return this.skeletons[index];
  23702. }
  23703. }
  23704. return null;
  23705. };
  23706. Scene.prototype.getMorphTargetManagerById = function (id) {
  23707. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23708. if (this.morphTargetManagers[index].uniqueId === id) {
  23709. return this.morphTargetManagers[index];
  23710. }
  23711. }
  23712. return null;
  23713. };
  23714. Scene.prototype.isActiveMesh = function (mesh) {
  23715. return (this._activeMeshes.indexOf(mesh) !== -1);
  23716. };
  23717. /**
  23718. * Return a the first highlight layer of the scene with a given name.
  23719. * @param name The name of the highlight layer to look for.
  23720. * @return The highlight layer if found otherwise null.
  23721. */
  23722. Scene.prototype.getHighlightLayerByName = function (name) {
  23723. for (var index = 0; index < this.effectLayers.length; index++) {
  23724. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23725. return this.effectLayers[index];
  23726. }
  23727. }
  23728. return null;
  23729. };
  23730. /**
  23731. * Return a the first highlight layer of the scene with a given name.
  23732. * @param name The name of the highlight layer to look for.
  23733. * @return The highlight layer if found otherwise null.
  23734. */
  23735. Scene.prototype.getGlowLayerByName = function (name) {
  23736. for (var index = 0; index < this.effectLayers.length; index++) {
  23737. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23738. return this.effectLayers[index];
  23739. }
  23740. }
  23741. return null;
  23742. };
  23743. Object.defineProperty(Scene.prototype, "uid", {
  23744. /**
  23745. * Return a unique id as a string which can serve as an identifier for the scene
  23746. */
  23747. get: function () {
  23748. if (!this._uid) {
  23749. this._uid = BABYLON.Tools.RandomId();
  23750. }
  23751. return this._uid;
  23752. },
  23753. enumerable: true,
  23754. configurable: true
  23755. });
  23756. /**
  23757. * Add an externaly attached data from its key.
  23758. * This method call will fail and return false, if such key already exists.
  23759. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23760. * @param key the unique key that identifies the data
  23761. * @param data the data object to associate to the key for this Engine instance
  23762. * @return true if no such key were already present and the data was added successfully, false otherwise
  23763. */
  23764. Scene.prototype.addExternalData = function (key, data) {
  23765. if (!this._externalData) {
  23766. this._externalData = new BABYLON.StringDictionary();
  23767. }
  23768. return this._externalData.add(key, data);
  23769. };
  23770. /**
  23771. * Get an externaly attached data from its key
  23772. * @param key the unique key that identifies the data
  23773. * @return the associated data, if present (can be null), or undefined if not present
  23774. */
  23775. Scene.prototype.getExternalData = function (key) {
  23776. if (!this._externalData) {
  23777. return null;
  23778. }
  23779. return this._externalData.get(key);
  23780. };
  23781. /**
  23782. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23783. * @param key the unique key that identifies the data
  23784. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23785. * @return the associated data, can be null if the factory returned null.
  23786. */
  23787. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23788. if (!this._externalData) {
  23789. this._externalData = new BABYLON.StringDictionary();
  23790. }
  23791. return this._externalData.getOrAddWithFactory(key, factory);
  23792. };
  23793. /**
  23794. * Remove an externaly attached data from the Engine instance
  23795. * @param key the unique key that identifies the data
  23796. * @return true if the data was successfully removed, false if it doesn't exist
  23797. */
  23798. Scene.prototype.removeExternalData = function (key) {
  23799. return this._externalData.remove(key);
  23800. };
  23801. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23802. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23803. if (mesh.showSubMeshesBoundingBox) {
  23804. var boundingInfo = subMesh.getBoundingInfo();
  23805. if (boundingInfo !== null && boundingInfo !== undefined) {
  23806. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23807. }
  23808. }
  23809. var material = subMesh.getMaterial();
  23810. if (material !== null && material !== undefined) {
  23811. // Render targets
  23812. if (material.getRenderTargetTextures !== undefined) {
  23813. if (this._processedMaterials.indexOf(material) === -1) {
  23814. this._processedMaterials.push(material);
  23815. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23816. }
  23817. }
  23818. // Dispatch
  23819. this._activeIndices.addCount(subMesh.indexCount, false);
  23820. this._renderingManager.dispatch(subMesh, mesh, material);
  23821. }
  23822. }
  23823. };
  23824. Scene.prototype._isInIntermediateRendering = function () {
  23825. return this._intermediateRendering;
  23826. };
  23827. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23828. this._activeMeshCandidateProvider = provider;
  23829. };
  23830. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23831. return this._activeMeshCandidateProvider;
  23832. };
  23833. /**
  23834. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23835. */
  23836. Scene.prototype.freezeActiveMeshes = function () {
  23837. this._evaluateActiveMeshes();
  23838. this._activeMeshesFrozen = true;
  23839. return this;
  23840. };
  23841. /**
  23842. * Use this function to restart evaluating active meshes on every frame
  23843. */
  23844. Scene.prototype.unfreezeActiveMeshes = function () {
  23845. this._activeMeshesFrozen = false;
  23846. return this;
  23847. };
  23848. Scene.prototype._evaluateActiveMeshes = function () {
  23849. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23850. return;
  23851. }
  23852. if (!this.activeCamera) {
  23853. return;
  23854. }
  23855. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23856. this.activeCamera._activeMeshes.reset();
  23857. this._activeMeshes.reset();
  23858. this._renderingManager.reset();
  23859. this._processedMaterials.reset();
  23860. this._activeParticleSystems.reset();
  23861. this._activeSkeletons.reset();
  23862. this._softwareSkinnedMeshes.reset();
  23863. if (this._boundingBoxRenderer) {
  23864. this._boundingBoxRenderer.reset();
  23865. }
  23866. // Meshes
  23867. var meshes;
  23868. var len;
  23869. var checkIsEnabled = true;
  23870. // Determine mesh candidates
  23871. if (this._activeMeshCandidateProvider !== undefined) {
  23872. // Use _activeMeshCandidateProvider
  23873. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23874. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23875. if (meshes !== undefined) {
  23876. len = meshes.length;
  23877. }
  23878. else {
  23879. len = 0;
  23880. }
  23881. }
  23882. else if (this._selectionOctree !== undefined) {
  23883. // Octree
  23884. var selection = this._selectionOctree.select(this._frustumPlanes);
  23885. meshes = selection.data;
  23886. len = selection.length;
  23887. }
  23888. else {
  23889. // Full scene traversal
  23890. len = this.meshes.length;
  23891. meshes = this.meshes;
  23892. }
  23893. // Check each mesh
  23894. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23895. mesh = meshes[meshIndex];
  23896. if (mesh.isBlocked) {
  23897. continue;
  23898. }
  23899. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23900. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23901. continue;
  23902. }
  23903. mesh.computeWorldMatrix();
  23904. // Intersections
  23905. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23906. this._meshesForIntersections.pushNoDuplicate(mesh);
  23907. }
  23908. // Switch to current LOD
  23909. meshLOD = mesh.getLOD(this.activeCamera);
  23910. if (meshLOD === undefined || meshLOD === null) {
  23911. continue;
  23912. }
  23913. mesh._preActivate();
  23914. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23915. this._activeMeshes.push(mesh);
  23916. this.activeCamera._activeMeshes.push(mesh);
  23917. mesh._activate(this._renderId);
  23918. if (meshLOD !== mesh) {
  23919. meshLOD._activate(this._renderId);
  23920. }
  23921. this._activeMesh(mesh, meshLOD);
  23922. }
  23923. }
  23924. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23925. // Particle systems
  23926. if (this.particlesEnabled) {
  23927. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23928. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23929. var particleSystem = this.particleSystems[particleIndex];
  23930. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23931. continue;
  23932. }
  23933. var emitter = particleSystem.emitter;
  23934. if (!emitter.position || emitter.isEnabled()) {
  23935. this._activeParticleSystems.push(particleSystem);
  23936. particleSystem.animate();
  23937. this._renderingManager.dispatchParticles(particleSystem);
  23938. }
  23939. }
  23940. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23941. }
  23942. };
  23943. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23944. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23945. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23946. mesh.skeleton.prepare();
  23947. }
  23948. if (!mesh.computeBonesUsingShaders) {
  23949. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23950. }
  23951. }
  23952. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23953. var boundingInfo = sourceMesh.getBoundingInfo();
  23954. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23955. }
  23956. if (mesh !== undefined && mesh !== null
  23957. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23958. // Submeshes Octrees
  23959. var len;
  23960. var subMeshes;
  23961. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23962. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23963. len = intersections.length;
  23964. subMeshes = intersections.data;
  23965. }
  23966. else {
  23967. subMeshes = mesh.subMeshes;
  23968. len = subMeshes.length;
  23969. }
  23970. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23971. subMesh = subMeshes[subIndex];
  23972. this._evaluateSubMesh(subMesh, mesh);
  23973. }
  23974. }
  23975. };
  23976. Scene.prototype.updateTransformMatrix = function (force) {
  23977. if (!this.activeCamera) {
  23978. return;
  23979. }
  23980. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23981. };
  23982. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23983. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23984. };
  23985. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23986. if (camera && camera._skipRendering) {
  23987. return;
  23988. }
  23989. var engine = this._engine;
  23990. this.activeCamera = camera;
  23991. if (!this.activeCamera)
  23992. throw new Error("Active camera not set");
  23993. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23994. // Viewport
  23995. engine.setViewport(this.activeCamera.viewport);
  23996. // Camera
  23997. this.resetCachedMaterial();
  23998. this._renderId++;
  23999. this.updateTransformMatrix();
  24000. if (camera._alternateCamera) {
  24001. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24002. this._alternateRendering = true;
  24003. }
  24004. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24005. // Meshes
  24006. this._evaluateActiveMeshes();
  24007. // Software skinning
  24008. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24009. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24010. mesh.applySkeleton(mesh.skeleton);
  24011. }
  24012. // Render targets
  24013. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24014. var needsRestoreFrameBuffer = false;
  24015. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24016. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24017. }
  24018. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24019. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24020. }
  24021. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24022. this._intermediateRendering = true;
  24023. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24024. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24025. var renderTarget = this._renderTargets.data[renderIndex];
  24026. if (renderTarget._shouldRender()) {
  24027. this._renderId++;
  24028. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24029. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24030. }
  24031. }
  24032. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24033. this._intermediateRendering = false;
  24034. this._renderId++;
  24035. needsRestoreFrameBuffer = true; // Restore back buffer
  24036. }
  24037. // Render EffecttLayer Texture
  24038. var stencilState = this._engine.getStencilBuffer();
  24039. var renderEffects = false;
  24040. var needStencil = false;
  24041. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24042. this._intermediateRendering = true;
  24043. for (var i = 0; i < this.effectLayers.length; i++) {
  24044. var effectLayer = this.effectLayers[i];
  24045. if (effectLayer.shouldRender() &&
  24046. (!effectLayer.camera ||
  24047. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24048. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24049. renderEffects = true;
  24050. needStencil = needStencil || effectLayer.needStencil();
  24051. var renderTarget = effectLayer._mainTexture;
  24052. if (renderTarget._shouldRender()) {
  24053. this._renderId++;
  24054. renderTarget.render(false, false);
  24055. needsRestoreFrameBuffer = true;
  24056. }
  24057. }
  24058. }
  24059. this._intermediateRendering = false;
  24060. this._renderId++;
  24061. }
  24062. if (needsRestoreFrameBuffer) {
  24063. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24064. }
  24065. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24066. // Prepare Frame
  24067. this.postProcessManager._prepareFrame();
  24068. // Backgrounds
  24069. var layerIndex;
  24070. var layer;
  24071. if (this.layers.length) {
  24072. engine.setDepthBuffer(false);
  24073. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24074. layer = this.layers[layerIndex];
  24075. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24076. layer.render();
  24077. }
  24078. }
  24079. engine.setDepthBuffer(true);
  24080. }
  24081. // Activate effect Layer stencil
  24082. if (needStencil) {
  24083. this._engine.setStencilBuffer(true);
  24084. }
  24085. // Render
  24086. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24087. this._renderingManager.render(null, null, true, true);
  24088. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24089. // Restore effect Layer stencil
  24090. if (needStencil) {
  24091. this._engine.setStencilBuffer(stencilState);
  24092. }
  24093. // Bounding boxes
  24094. if (this._boundingBoxRenderer) {
  24095. this._boundingBoxRenderer.render();
  24096. }
  24097. // Lens flares
  24098. if (this.lensFlaresEnabled) {
  24099. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24100. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24101. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24102. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24103. lensFlareSystem.render();
  24104. }
  24105. }
  24106. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24107. }
  24108. // Foregrounds
  24109. if (this.layers.length) {
  24110. engine.setDepthBuffer(false);
  24111. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24112. layer = this.layers[layerIndex];
  24113. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24114. layer.render();
  24115. }
  24116. }
  24117. engine.setDepthBuffer(true);
  24118. }
  24119. // Effect Layer
  24120. if (renderEffects) {
  24121. engine.setDepthBuffer(false);
  24122. for (var i = 0; i < this.effectLayers.length; i++) {
  24123. if (this.effectLayers[i].shouldRender()) {
  24124. this.effectLayers[i].render();
  24125. }
  24126. }
  24127. engine.setDepthBuffer(true);
  24128. }
  24129. // Finalize frame
  24130. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24131. // Reset some special arrays
  24132. this._renderTargets.reset();
  24133. this._alternateRendering = false;
  24134. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24135. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24136. };
  24137. Scene.prototype._processSubCameras = function (camera) {
  24138. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24139. this._renderForCamera(camera);
  24140. return;
  24141. }
  24142. // rig cameras
  24143. for (var index = 0; index < camera._rigCameras.length; index++) {
  24144. this._renderForCamera(camera._rigCameras[index], camera);
  24145. }
  24146. this.activeCamera = camera;
  24147. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24148. };
  24149. Scene.prototype._checkIntersections = function () {
  24150. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24151. var sourceMesh = this._meshesForIntersections.data[index];
  24152. if (!sourceMesh.actionManager) {
  24153. continue;
  24154. }
  24155. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24156. var action = sourceMesh.actionManager.actions[actionIndex];
  24157. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24158. var parameters = action.getTriggerParameter();
  24159. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24160. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24161. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24162. if (areIntersecting && currentIntersectionInProgress === -1) {
  24163. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24164. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24165. sourceMesh._intersectionsInProgress.push(otherMesh);
  24166. }
  24167. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24168. sourceMesh._intersectionsInProgress.push(otherMesh);
  24169. }
  24170. }
  24171. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24172. //They intersected, and now they don't.
  24173. //is this trigger an exit trigger? execute an event.
  24174. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24175. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24176. }
  24177. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24178. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24179. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24180. }
  24181. }
  24182. }
  24183. }
  24184. }
  24185. };
  24186. Scene.prototype.render = function () {
  24187. if (this.isDisposed) {
  24188. return;
  24189. }
  24190. this._activeParticles.fetchNewFrame();
  24191. this._totalVertices.fetchNewFrame();
  24192. this._activeIndices.fetchNewFrame();
  24193. this._activeBones.fetchNewFrame();
  24194. this._meshesForIntersections.reset();
  24195. this.resetCachedMaterial();
  24196. this.onBeforeAnimationsObservable.notifyObservers(this);
  24197. // Actions
  24198. if (this.actionManager) {
  24199. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24200. }
  24201. //Simplification Queue
  24202. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24203. this.simplificationQueue.executeNext();
  24204. }
  24205. if (this._engine.isDeterministicLockStep()) {
  24206. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24207. var defaultFPS = (60.0 / 1000.0);
  24208. var defaultFrameTime = 1000 / 60; // frame time in MS
  24209. if (this._physicsEngine) {
  24210. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24211. }
  24212. var stepsTaken = 0;
  24213. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24214. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24215. internalSteps = Math.min(internalSteps, maxSubSteps);
  24216. do {
  24217. this.onBeforeStepObservable.notifyObservers(this);
  24218. // Animations
  24219. this._animationRatio = defaultFrameTime * defaultFPS;
  24220. this._animate();
  24221. this.onAfterAnimationsObservable.notifyObservers(this);
  24222. // Physics
  24223. if (this._physicsEngine) {
  24224. this.onBeforePhysicsObservable.notifyObservers(this);
  24225. this._physicsEngine._step(defaultFrameTime / 1000);
  24226. this.onAfterPhysicsObservable.notifyObservers(this);
  24227. }
  24228. this.onAfterStepObservable.notifyObservers(this);
  24229. this._currentStepId++;
  24230. stepsTaken++;
  24231. deltaTime -= defaultFrameTime;
  24232. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24233. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24234. }
  24235. else {
  24236. // Animations
  24237. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24238. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24239. this._animate();
  24240. this.onAfterAnimationsObservable.notifyObservers(this);
  24241. // Physics
  24242. if (this._physicsEngine) {
  24243. this.onBeforePhysicsObservable.notifyObservers(this);
  24244. this._physicsEngine._step(deltaTime / 1000.0);
  24245. this.onAfterPhysicsObservable.notifyObservers(this);
  24246. }
  24247. }
  24248. // update gamepad manager
  24249. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24250. this._gamepadManager._checkGamepadsStatus();
  24251. }
  24252. // Before render
  24253. this.onBeforeRenderObservable.notifyObservers(this);
  24254. // Update Cameras
  24255. if (this.activeCameras.length > 0) {
  24256. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24257. var camera = this.activeCameras[cameraIndex];
  24258. camera.update();
  24259. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24260. // rig cameras
  24261. for (var index = 0; index < camera._rigCameras.length; index++) {
  24262. camera._rigCameras[index].update();
  24263. }
  24264. }
  24265. }
  24266. }
  24267. else if (this.activeCamera) {
  24268. this.activeCamera.update();
  24269. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24270. // rig cameras
  24271. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24272. this.activeCamera._rigCameras[index].update();
  24273. }
  24274. }
  24275. }
  24276. // Customs render targets
  24277. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24278. var engine = this.getEngine();
  24279. var currentActiveCamera = this.activeCamera;
  24280. if (this.renderTargetsEnabled) {
  24281. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24282. this._intermediateRendering = true;
  24283. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24284. var renderTarget = this.customRenderTargets[customIndex];
  24285. if (renderTarget._shouldRender()) {
  24286. this._renderId++;
  24287. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24288. if (!this.activeCamera)
  24289. throw new Error("Active camera not set");
  24290. // Viewport
  24291. engine.setViewport(this.activeCamera.viewport);
  24292. // Camera
  24293. this.updateTransformMatrix();
  24294. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24295. }
  24296. }
  24297. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24298. this._intermediateRendering = false;
  24299. this._renderId++;
  24300. }
  24301. // Restore back buffer
  24302. if (this.customRenderTargets.length > 0) {
  24303. engine.restoreDefaultFramebuffer();
  24304. }
  24305. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24306. this.activeCamera = currentActiveCamera;
  24307. // Procedural textures
  24308. if (this.proceduralTexturesEnabled) {
  24309. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24310. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24311. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24312. if (proceduralTexture._shouldRender()) {
  24313. proceduralTexture.render();
  24314. }
  24315. }
  24316. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24317. }
  24318. // Clear
  24319. if (this.autoClearDepthAndStencil || this.autoClear) {
  24320. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24321. }
  24322. // Shadows
  24323. if (this.shadowsEnabled) {
  24324. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24325. var light = this.lights[lightIndex];
  24326. var shadowGenerator = light.getShadowGenerator();
  24327. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24328. var shadowMap = (shadowGenerator.getShadowMap());
  24329. if (this.textures.indexOf(shadowMap) !== -1) {
  24330. this._renderTargets.push(shadowMap);
  24331. }
  24332. }
  24333. }
  24334. }
  24335. // Depth renderer
  24336. for (var key in this._depthRenderer) {
  24337. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24338. }
  24339. // Geometry renderer
  24340. if (this._geometryBufferRenderer) {
  24341. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24342. }
  24343. // RenderPipeline
  24344. if (this._postProcessRenderPipelineManager) {
  24345. this._postProcessRenderPipelineManager.update();
  24346. }
  24347. // Multi-cameras?
  24348. if (this.activeCameras.length > 0) {
  24349. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24350. if (cameraIndex > 0) {
  24351. this._engine.clear(null, false, true, true);
  24352. }
  24353. this._processSubCameras(this.activeCameras[cameraIndex]);
  24354. }
  24355. }
  24356. else {
  24357. if (!this.activeCamera) {
  24358. throw new Error("No camera defined");
  24359. }
  24360. this._processSubCameras(this.activeCamera);
  24361. }
  24362. // Intersection checks
  24363. this._checkIntersections();
  24364. // Update the audio listener attached to the camera
  24365. if (BABYLON.AudioEngine) {
  24366. this._updateAudioParameters();
  24367. }
  24368. // After render
  24369. if (this.afterRender) {
  24370. this.afterRender();
  24371. }
  24372. this.onAfterRenderObservable.notifyObservers(this);
  24373. // Cleaning
  24374. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24375. var data = this._toBeDisposed.data[index];
  24376. if (data) {
  24377. data.dispose();
  24378. }
  24379. this._toBeDisposed[index] = null;
  24380. }
  24381. this._toBeDisposed.reset();
  24382. if (this.dumpNextRenderTargets) {
  24383. this.dumpNextRenderTargets = false;
  24384. }
  24385. this._activeBones.addCount(0, true);
  24386. this._activeIndices.addCount(0, true);
  24387. this._activeParticles.addCount(0, true);
  24388. };
  24389. Scene.prototype._updateAudioParameters = function () {
  24390. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24391. return;
  24392. }
  24393. var listeningCamera;
  24394. var audioEngine = BABYLON.Engine.audioEngine;
  24395. if (this.activeCameras.length > 0) {
  24396. listeningCamera = this.activeCameras[0];
  24397. }
  24398. else {
  24399. listeningCamera = this.activeCamera;
  24400. }
  24401. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24402. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24403. // for VR cameras
  24404. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24405. listeningCamera = listeningCamera.rigCameras[0];
  24406. }
  24407. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24408. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24409. cameraDirection.normalize();
  24410. // To avoid some errors on GearVR
  24411. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24412. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24413. }
  24414. var i;
  24415. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24416. var sound = this.mainSoundTrack.soundCollection[i];
  24417. if (sound.useCustomAttenuation) {
  24418. sound.updateDistanceFromListener();
  24419. }
  24420. }
  24421. for (i = 0; i < this.soundTracks.length; i++) {
  24422. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24423. sound = this.soundTracks[i].soundCollection[j];
  24424. if (sound.useCustomAttenuation) {
  24425. sound.updateDistanceFromListener();
  24426. }
  24427. }
  24428. }
  24429. }
  24430. };
  24431. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24432. // Audio
  24433. get: function () {
  24434. return this._audioEnabled;
  24435. },
  24436. set: function (value) {
  24437. this._audioEnabled = value;
  24438. if (BABYLON.AudioEngine) {
  24439. if (this._audioEnabled) {
  24440. this._enableAudio();
  24441. }
  24442. else {
  24443. this._disableAudio();
  24444. }
  24445. }
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Scene.prototype._disableAudio = function () {
  24451. var i;
  24452. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24453. this.mainSoundTrack.soundCollection[i].pause();
  24454. }
  24455. for (i = 0; i < this.soundTracks.length; i++) {
  24456. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24457. this.soundTracks[i].soundCollection[j].pause();
  24458. }
  24459. }
  24460. };
  24461. Scene.prototype._enableAudio = function () {
  24462. var i;
  24463. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24464. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24465. this.mainSoundTrack.soundCollection[i].play();
  24466. }
  24467. }
  24468. for (i = 0; i < this.soundTracks.length; i++) {
  24469. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24470. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24471. this.soundTracks[i].soundCollection[j].play();
  24472. }
  24473. }
  24474. }
  24475. };
  24476. Object.defineProperty(Scene.prototype, "headphone", {
  24477. get: function () {
  24478. return this._headphone;
  24479. },
  24480. set: function (value) {
  24481. this._headphone = value;
  24482. if (BABYLON.AudioEngine) {
  24483. if (this._headphone) {
  24484. this._switchAudioModeForHeadphones();
  24485. }
  24486. else {
  24487. this._switchAudioModeForNormalSpeakers();
  24488. }
  24489. }
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Scene.prototype._switchAudioModeForHeadphones = function () {
  24495. this.mainSoundTrack.switchPanningModelToHRTF();
  24496. for (var i = 0; i < this.soundTracks.length; i++) {
  24497. this.soundTracks[i].switchPanningModelToHRTF();
  24498. }
  24499. };
  24500. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24501. this.mainSoundTrack.switchPanningModelToEqualPower();
  24502. for (var i = 0; i < this.soundTracks.length; i++) {
  24503. this.soundTracks[i].switchPanningModelToEqualPower();
  24504. }
  24505. };
  24506. /**
  24507. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24508. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24509. * @returns the created depth renderer
  24510. */
  24511. Scene.prototype.enableDepthRenderer = function (camera) {
  24512. camera = camera || this.activeCamera;
  24513. if (!camera) {
  24514. throw "No camera available to enable depth renderer";
  24515. }
  24516. if (!this._depthRenderer[camera.id]) {
  24517. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24518. }
  24519. return this._depthRenderer[camera.id];
  24520. };
  24521. /**
  24522. * Disables a depth renderer for a given camera
  24523. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24524. */
  24525. Scene.prototype.disableDepthRenderer = function (camera) {
  24526. camera = camera || this.activeCamera;
  24527. if (!camera || !this._depthRenderer[camera.id]) {
  24528. return;
  24529. }
  24530. this._depthRenderer[camera.id].dispose();
  24531. delete this._depthRenderer[camera.id];
  24532. };
  24533. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24534. if (ratio === void 0) { ratio = 1; }
  24535. if (this._geometryBufferRenderer) {
  24536. return this._geometryBufferRenderer;
  24537. }
  24538. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24539. if (!this._geometryBufferRenderer.isSupported) {
  24540. this._geometryBufferRenderer = null;
  24541. }
  24542. return this._geometryBufferRenderer;
  24543. };
  24544. Scene.prototype.disableGeometryBufferRenderer = function () {
  24545. if (!this._geometryBufferRenderer) {
  24546. return;
  24547. }
  24548. this._geometryBufferRenderer.dispose();
  24549. this._geometryBufferRenderer = null;
  24550. };
  24551. Scene.prototype.freezeMaterials = function () {
  24552. for (var i = 0; i < this.materials.length; i++) {
  24553. this.materials[i].freeze();
  24554. }
  24555. };
  24556. Scene.prototype.unfreezeMaterials = function () {
  24557. for (var i = 0; i < this.materials.length; i++) {
  24558. this.materials[i].unfreeze();
  24559. }
  24560. };
  24561. Scene.prototype.dispose = function () {
  24562. this.beforeRender = null;
  24563. this.afterRender = null;
  24564. this.skeletons = [];
  24565. this.morphTargetManagers = [];
  24566. this.importedMeshesFiles = new Array();
  24567. this.stopAllAnimations();
  24568. this.resetCachedMaterial();
  24569. for (var key in this._depthRenderer) {
  24570. this._depthRenderer[key].dispose();
  24571. }
  24572. if (this._gamepadManager) {
  24573. this._gamepadManager.dispose();
  24574. this._gamepadManager = null;
  24575. }
  24576. // Smart arrays
  24577. if (this.activeCamera) {
  24578. this.activeCamera._activeMeshes.dispose();
  24579. this.activeCamera = null;
  24580. }
  24581. this._activeMeshes.dispose();
  24582. this._renderingManager.dispose();
  24583. this._processedMaterials.dispose();
  24584. this._activeParticleSystems.dispose();
  24585. this._activeSkeletons.dispose();
  24586. this._softwareSkinnedMeshes.dispose();
  24587. this._renderTargets.dispose();
  24588. if (this._boundingBoxRenderer) {
  24589. this._boundingBoxRenderer.dispose();
  24590. }
  24591. this._meshesForIntersections.dispose();
  24592. this._toBeDisposed.dispose();
  24593. // Abort active requests
  24594. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24595. var request = _a[_i];
  24596. request.abort();
  24597. }
  24598. // Debug layer
  24599. if (this._debugLayer) {
  24600. this._debugLayer.hide();
  24601. }
  24602. // Events
  24603. this.onDisposeObservable.notifyObservers(this);
  24604. this.onDisposeObservable.clear();
  24605. this.onBeforeRenderObservable.clear();
  24606. this.onAfterRenderObservable.clear();
  24607. this.OnBeforeRenderTargetsRenderObservable.clear();
  24608. this.OnAfterRenderTargetsRenderObservable.clear();
  24609. this.onAfterStepObservable.clear();
  24610. this.onBeforeStepObservable.clear();
  24611. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24612. this.onAfterActiveMeshesEvaluationObservable.clear();
  24613. this.onBeforeParticlesRenderingObservable.clear();
  24614. this.onAfterParticlesRenderingObservable.clear();
  24615. this.onBeforeSpritesRenderingObservable.clear();
  24616. this.onAfterSpritesRenderingObservable.clear();
  24617. this.onBeforeDrawPhaseObservable.clear();
  24618. this.onAfterDrawPhaseObservable.clear();
  24619. this.onBeforePhysicsObservable.clear();
  24620. this.onAfterPhysicsObservable.clear();
  24621. this.onBeforeAnimationsObservable.clear();
  24622. this.onAfterAnimationsObservable.clear();
  24623. this.onDataLoadedObservable.clear();
  24624. this.detachControl();
  24625. // Release sounds & sounds tracks
  24626. if (BABYLON.AudioEngine) {
  24627. this.disposeSounds();
  24628. }
  24629. // VR Helper
  24630. if (this.VRHelper) {
  24631. this.VRHelper.dispose();
  24632. }
  24633. // Detach cameras
  24634. var canvas = this._engine.getRenderingCanvas();
  24635. if (canvas) {
  24636. var index;
  24637. for (index = 0; index < this.cameras.length; index++) {
  24638. this.cameras[index].detachControl(canvas);
  24639. }
  24640. }
  24641. // Release animation groups
  24642. while (this.animationGroups.length) {
  24643. this.animationGroups[0].dispose();
  24644. }
  24645. // Release lights
  24646. while (this.lights.length) {
  24647. this.lights[0].dispose();
  24648. }
  24649. // Release meshes
  24650. while (this.meshes.length) {
  24651. this.meshes[0].dispose(true);
  24652. }
  24653. while (this.transformNodes.length) {
  24654. this.removeTransformNode(this.transformNodes[0]);
  24655. }
  24656. // Release cameras
  24657. while (this.cameras.length) {
  24658. this.cameras[0].dispose();
  24659. }
  24660. // Release materials
  24661. if (this.defaultMaterial) {
  24662. this.defaultMaterial.dispose();
  24663. }
  24664. while (this.multiMaterials.length) {
  24665. this.multiMaterials[0].dispose();
  24666. }
  24667. while (this.materials.length) {
  24668. this.materials[0].dispose();
  24669. }
  24670. // Release particles
  24671. while (this.particleSystems.length) {
  24672. this.particleSystems[0].dispose();
  24673. }
  24674. // Release sprites
  24675. while (this.spriteManagers.length) {
  24676. this.spriteManagers[0].dispose();
  24677. }
  24678. // Release postProcesses
  24679. while (this.postProcesses.length) {
  24680. this.postProcesses[0].dispose();
  24681. }
  24682. // Release layers
  24683. while (this.layers.length) {
  24684. this.layers[0].dispose();
  24685. }
  24686. while (this.effectLayers.length) {
  24687. this.effectLayers[0].dispose();
  24688. }
  24689. // Release textures
  24690. while (this.textures.length) {
  24691. this.textures[0].dispose();
  24692. }
  24693. // Release UBO
  24694. this._sceneUbo.dispose();
  24695. if (this._alternateSceneUbo) {
  24696. this._alternateSceneUbo.dispose();
  24697. }
  24698. // Post-processes
  24699. this.postProcessManager.dispose();
  24700. if (this._postProcessRenderPipelineManager) {
  24701. this._postProcessRenderPipelineManager.dispose();
  24702. }
  24703. // Physics
  24704. if (this._physicsEngine) {
  24705. this.disablePhysicsEngine();
  24706. }
  24707. // Remove from engine
  24708. index = this._engine.scenes.indexOf(this);
  24709. if (index > -1) {
  24710. this._engine.scenes.splice(index, 1);
  24711. }
  24712. this._engine.wipeCaches(true);
  24713. this._isDisposed = true;
  24714. };
  24715. Object.defineProperty(Scene.prototype, "isDisposed", {
  24716. get: function () {
  24717. return this._isDisposed;
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. // Release sounds & sounds tracks
  24723. Scene.prototype.disposeSounds = function () {
  24724. if (!this._mainSoundTrack) {
  24725. return;
  24726. }
  24727. this.mainSoundTrack.dispose();
  24728. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24729. this.soundTracks[scIndex].dispose();
  24730. }
  24731. };
  24732. // Octrees
  24733. /**
  24734. * Get the world extend vectors with an optional filter
  24735. *
  24736. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24737. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24738. */
  24739. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24740. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24741. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24742. filterPredicate = filterPredicate || (function () { return true; });
  24743. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24744. mesh.computeWorldMatrix(true);
  24745. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24746. return;
  24747. }
  24748. var boundingInfo = mesh.getBoundingInfo();
  24749. var minBox = boundingInfo.boundingBox.minimumWorld;
  24750. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24751. BABYLON.Tools.CheckExtends(minBox, min, max);
  24752. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24753. });
  24754. return {
  24755. min: min,
  24756. max: max
  24757. };
  24758. };
  24759. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24760. if (maxCapacity === void 0) { maxCapacity = 64; }
  24761. if (maxDepth === void 0) { maxDepth = 2; }
  24762. if (!this._selectionOctree) {
  24763. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24764. }
  24765. var worldExtends = this.getWorldExtends();
  24766. // Update octree
  24767. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24768. return this._selectionOctree;
  24769. };
  24770. // Picking
  24771. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24772. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24773. var result = BABYLON.Ray.Zero();
  24774. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24775. return result;
  24776. };
  24777. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24778. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24779. var engine = this._engine;
  24780. if (!camera) {
  24781. if (!this.activeCamera)
  24782. throw new Error("Active camera not set");
  24783. camera = this.activeCamera;
  24784. }
  24785. var cameraViewport = camera.viewport;
  24786. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24787. // Moving coordinates to local viewport world
  24788. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24789. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24790. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24791. return this;
  24792. };
  24793. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24794. var result = BABYLON.Ray.Zero();
  24795. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24796. return result;
  24797. };
  24798. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24799. if (!BABYLON.PickingInfo) {
  24800. return this;
  24801. }
  24802. var engine = this._engine;
  24803. if (!camera) {
  24804. if (!this.activeCamera)
  24805. throw new Error("Active camera not set");
  24806. camera = this.activeCamera;
  24807. }
  24808. var cameraViewport = camera.viewport;
  24809. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24810. var identity = BABYLON.Matrix.Identity();
  24811. // Moving coordinates to local viewport world
  24812. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24813. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24814. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24815. return this;
  24816. };
  24817. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24818. if (!BABYLON.PickingInfo) {
  24819. return null;
  24820. }
  24821. var pickingInfo = null;
  24822. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24823. var mesh = this.meshes[meshIndex];
  24824. if (predicate) {
  24825. if (!predicate(mesh)) {
  24826. continue;
  24827. }
  24828. }
  24829. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24830. continue;
  24831. }
  24832. var world = mesh.getWorldMatrix();
  24833. var ray = rayFunction(world);
  24834. var result = mesh.intersects(ray, fastCheck);
  24835. if (!result || !result.hit)
  24836. continue;
  24837. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24838. continue;
  24839. pickingInfo = result;
  24840. if (fastCheck) {
  24841. break;
  24842. }
  24843. }
  24844. return pickingInfo || new BABYLON.PickingInfo();
  24845. };
  24846. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24847. if (!BABYLON.PickingInfo) {
  24848. return null;
  24849. }
  24850. var pickingInfos = new Array();
  24851. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24852. var mesh = this.meshes[meshIndex];
  24853. if (predicate) {
  24854. if (!predicate(mesh)) {
  24855. continue;
  24856. }
  24857. }
  24858. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24859. continue;
  24860. }
  24861. var world = mesh.getWorldMatrix();
  24862. var ray = rayFunction(world);
  24863. var result = mesh.intersects(ray, false);
  24864. if (!result || !result.hit)
  24865. continue;
  24866. pickingInfos.push(result);
  24867. }
  24868. return pickingInfos;
  24869. };
  24870. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24871. if (!BABYLON.PickingInfo) {
  24872. return null;
  24873. }
  24874. var pickingInfo = null;
  24875. if (!camera) {
  24876. if (!this.activeCamera) {
  24877. return null;
  24878. }
  24879. camera = this.activeCamera;
  24880. }
  24881. if (this.spriteManagers.length > 0) {
  24882. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24883. var spriteManager = this.spriteManagers[spriteIndex];
  24884. if (!spriteManager.isPickable) {
  24885. continue;
  24886. }
  24887. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24888. if (!result || !result.hit)
  24889. continue;
  24890. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24891. continue;
  24892. pickingInfo = result;
  24893. if (fastCheck) {
  24894. break;
  24895. }
  24896. }
  24897. }
  24898. return pickingInfo || new BABYLON.PickingInfo();
  24899. };
  24900. /** Launch a ray to try to pick a mesh in the scene
  24901. * @param x position on screen
  24902. * @param y position on screen
  24903. * @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
  24904. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24905. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24906. */
  24907. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24908. var _this = this;
  24909. if (!BABYLON.PickingInfo) {
  24910. return null;
  24911. }
  24912. return this._internalPick(function (world) {
  24913. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24914. return _this._tempPickingRay;
  24915. }, predicate, fastCheck);
  24916. };
  24917. /** Launch a ray to try to pick a sprite in the scene
  24918. * @param x position on screen
  24919. * @param y position on screen
  24920. * @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
  24921. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24922. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24923. */
  24924. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24925. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24926. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24927. };
  24928. /** Use the given ray to pick a mesh in the scene
  24929. * @param ray The ray to use to pick meshes
  24930. * @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
  24931. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24932. */
  24933. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24934. var _this = this;
  24935. return this._internalPick(function (world) {
  24936. if (!_this._pickWithRayInverseMatrix) {
  24937. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24938. }
  24939. world.invertToRef(_this._pickWithRayInverseMatrix);
  24940. if (!_this._cachedRayForTransform) {
  24941. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24942. }
  24943. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24944. return _this._cachedRayForTransform;
  24945. }, predicate, fastCheck);
  24946. };
  24947. /**
  24948. * Launch a ray to try to pick a mesh in the scene
  24949. * @param x X position on screen
  24950. * @param y Y position on screen
  24951. * @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
  24952. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24953. */
  24954. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24955. var _this = this;
  24956. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24957. };
  24958. /**
  24959. * Launch a ray to try to pick a mesh in the scene
  24960. * @param ray Ray to use
  24961. * @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
  24962. */
  24963. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24964. var _this = this;
  24965. return this._internalMultiPick(function (world) {
  24966. if (!_this._pickWithRayInverseMatrix) {
  24967. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24968. }
  24969. world.invertToRef(_this._pickWithRayInverseMatrix);
  24970. if (!_this._cachedRayForTransform) {
  24971. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24972. }
  24973. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24974. return _this._cachedRayForTransform;
  24975. }, predicate);
  24976. };
  24977. Scene.prototype.setPointerOverMesh = function (mesh) {
  24978. if (this._pointerOverMesh === mesh) {
  24979. return;
  24980. }
  24981. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24982. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24983. }
  24984. this._pointerOverMesh = mesh;
  24985. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24986. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24987. }
  24988. };
  24989. Scene.prototype.getPointerOverMesh = function () {
  24990. return this._pointerOverMesh;
  24991. };
  24992. Scene.prototype.setPointerOverSprite = function (sprite) {
  24993. if (this._pointerOverSprite === sprite) {
  24994. return;
  24995. }
  24996. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24997. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24998. }
  24999. this._pointerOverSprite = sprite;
  25000. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25001. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25002. }
  25003. };
  25004. Scene.prototype.getPointerOverSprite = function () {
  25005. return this._pointerOverSprite;
  25006. };
  25007. // Physics
  25008. Scene.prototype.getPhysicsEngine = function () {
  25009. return this._physicsEngine;
  25010. };
  25011. /**
  25012. * Enables physics to the current scene
  25013. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25014. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25015. * @return {boolean} was the physics engine initialized
  25016. */
  25017. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25018. if (gravity === void 0) { gravity = null; }
  25019. if (this._physicsEngine) {
  25020. return true;
  25021. }
  25022. try {
  25023. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25024. return true;
  25025. }
  25026. catch (e) {
  25027. BABYLON.Tools.Error(e.message);
  25028. return false;
  25029. }
  25030. };
  25031. Scene.prototype.disablePhysicsEngine = function () {
  25032. if (!this._physicsEngine) {
  25033. return;
  25034. }
  25035. this._physicsEngine.dispose();
  25036. this._physicsEngine = null;
  25037. };
  25038. Scene.prototype.isPhysicsEnabled = function () {
  25039. return this._physicsEngine !== undefined;
  25040. };
  25041. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25042. var mesh = compound.parts[0].mesh;
  25043. if (mesh.physicsImpostor) {
  25044. mesh.physicsImpostor.dispose();
  25045. mesh.physicsImpostor = null;
  25046. }
  25047. };
  25048. // Misc.
  25049. Scene.prototype._rebuildGeometries = function () {
  25050. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25051. var geometry = _a[_i];
  25052. geometry._rebuild();
  25053. }
  25054. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25055. var mesh = _c[_b];
  25056. mesh._rebuild();
  25057. }
  25058. if (this.postProcessManager) {
  25059. this.postProcessManager._rebuild();
  25060. }
  25061. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25062. var layer = _e[_d];
  25063. layer._rebuild();
  25064. }
  25065. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25066. var effectLayer = _g[_f];
  25067. effectLayer._rebuild();
  25068. }
  25069. if (this._boundingBoxRenderer) {
  25070. this._boundingBoxRenderer._rebuild();
  25071. }
  25072. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25073. var system = _j[_h];
  25074. system.rebuild();
  25075. }
  25076. if (this._postProcessRenderPipelineManager) {
  25077. this._postProcessRenderPipelineManager._rebuild();
  25078. }
  25079. };
  25080. Scene.prototype._rebuildTextures = function () {
  25081. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25082. var texture = _a[_i];
  25083. texture._rebuild();
  25084. }
  25085. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25086. };
  25087. /**
  25088. * Creates a default light for the scene.
  25089. * @param replace Whether to replace the existing lights in the scene.
  25090. */
  25091. Scene.prototype.createDefaultLight = function (replace) {
  25092. if (replace === void 0) { replace = false; }
  25093. // Dispose existing light in replace mode.
  25094. if (replace) {
  25095. if (this.lights) {
  25096. for (var i = 0; i < this.lights.length; i++) {
  25097. this.lights[i].dispose();
  25098. }
  25099. }
  25100. }
  25101. // Light
  25102. if (this.lights.length === 0) {
  25103. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25104. }
  25105. };
  25106. /**
  25107. * Creates a default camera for the scene.
  25108. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25109. * @param replace Whether to replace the existing active camera in the scene.
  25110. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25111. */
  25112. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25113. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25114. if (replace === void 0) { replace = false; }
  25115. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25116. // Dispose existing camera in replace mode.
  25117. if (replace) {
  25118. if (this.activeCamera) {
  25119. this.activeCamera.dispose();
  25120. this.activeCamera = null;
  25121. }
  25122. }
  25123. // Camera
  25124. if (!this.activeCamera) {
  25125. var worldExtends = this.getWorldExtends();
  25126. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25127. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25128. var camera;
  25129. var radius = worldSize.length() * 1.5;
  25130. // empty scene scenario!
  25131. if (!isFinite(radius)) {
  25132. radius = 1;
  25133. worldCenter.copyFromFloats(0, 0, 0);
  25134. }
  25135. if (createArcRotateCamera) {
  25136. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25137. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25138. arcRotateCamera.wheelPrecision = 100 / radius;
  25139. camera = arcRotateCamera;
  25140. }
  25141. else {
  25142. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25143. freeCamera.setTarget(worldCenter);
  25144. camera = freeCamera;
  25145. }
  25146. camera.minZ = radius * 0.01;
  25147. camera.maxZ = radius * 1000;
  25148. camera.speed = radius * 0.2;
  25149. this.activeCamera = camera;
  25150. var canvas = this.getEngine().getRenderingCanvas();
  25151. if (attachCameraControls && canvas) {
  25152. camera.attachControl(canvas);
  25153. }
  25154. }
  25155. };
  25156. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25157. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25158. if (replace === void 0) { replace = false; }
  25159. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25160. this.createDefaultLight(replace);
  25161. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25162. };
  25163. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25164. if (pbr === void 0) { pbr = false; }
  25165. if (scale === void 0) { scale = 1000; }
  25166. if (blur === void 0) { blur = 0; }
  25167. if (environmentTexture) {
  25168. this.environmentTexture = environmentTexture;
  25169. }
  25170. if (!this.environmentTexture) {
  25171. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25172. return null;
  25173. }
  25174. // Skybox
  25175. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25176. if (pbr) {
  25177. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25178. hdrSkyboxMaterial.backFaceCulling = false;
  25179. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25180. if (hdrSkyboxMaterial.reflectionTexture) {
  25181. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25182. }
  25183. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25184. hdrSkyboxMaterial.disableLighting = true;
  25185. hdrSkyboxMaterial.twoSidedLighting = true;
  25186. hdrSkybox.infiniteDistance = true;
  25187. hdrSkybox.material = hdrSkyboxMaterial;
  25188. }
  25189. else {
  25190. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25191. skyboxMaterial.backFaceCulling = false;
  25192. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25193. if (skyboxMaterial.reflectionTexture) {
  25194. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25195. }
  25196. skyboxMaterial.disableLighting = true;
  25197. hdrSkybox.infiniteDistance = true;
  25198. hdrSkybox.material = skyboxMaterial;
  25199. }
  25200. return hdrSkybox;
  25201. };
  25202. Scene.prototype.createDefaultEnvironment = function (options) {
  25203. if (BABYLON.EnvironmentHelper) {
  25204. return new BABYLON.EnvironmentHelper(options, this);
  25205. }
  25206. return null;
  25207. };
  25208. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25209. if (webVROptions === void 0) { webVROptions = {}; }
  25210. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25211. };
  25212. // Tags
  25213. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25214. if (tagsQuery === undefined) {
  25215. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25216. return list;
  25217. }
  25218. var listByTags = [];
  25219. forEach = forEach || (function (item) { return; });
  25220. for (var i in list) {
  25221. var item = list[i];
  25222. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25223. listByTags.push(item);
  25224. forEach(item);
  25225. }
  25226. }
  25227. return listByTags;
  25228. };
  25229. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25230. return this._getByTags(this.meshes, tagsQuery, forEach);
  25231. };
  25232. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25233. return this._getByTags(this.cameras, tagsQuery, forEach);
  25234. };
  25235. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25236. return this._getByTags(this.lights, tagsQuery, forEach);
  25237. };
  25238. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25239. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25240. };
  25241. /**
  25242. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25243. * This allowed control for front to back rendering or reversly depending of the special needs.
  25244. *
  25245. * @param renderingGroupId The rendering group id corresponding to its index
  25246. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25247. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25248. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25249. */
  25250. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25251. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25252. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25253. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25254. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25255. };
  25256. /**
  25257. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25258. *
  25259. * @param renderingGroupId The rendering group id corresponding to its index
  25260. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25261. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25262. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25263. */
  25264. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25265. if (depth === void 0) { depth = true; }
  25266. if (stencil === void 0) { stencil = true; }
  25267. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25268. };
  25269. /**
  25270. * Will flag all materials as dirty to trigger new shader compilation
  25271. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25272. */
  25273. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25274. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25275. var material = _a[_i];
  25276. if (predicate && !predicate(material)) {
  25277. continue;
  25278. }
  25279. material.markAsDirty(flag);
  25280. }
  25281. };
  25282. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25283. var _this = this;
  25284. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25285. this._activeRequests.push(request);
  25286. request.onCompleteObservable.add(function (request) {
  25287. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25288. });
  25289. return request;
  25290. };
  25291. /** @ignore */
  25292. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25293. var _this = this;
  25294. return new Promise(function (resolve, reject) {
  25295. _this._loadFile(url, function (data) {
  25296. resolve(data);
  25297. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25298. reject(exception);
  25299. });
  25300. });
  25301. };
  25302. // Statics
  25303. Scene._FOGMODE_NONE = 0;
  25304. Scene._FOGMODE_EXP = 1;
  25305. Scene._FOGMODE_EXP2 = 2;
  25306. Scene._FOGMODE_LINEAR = 3;
  25307. Scene._uniqueIdCounter = 0;
  25308. Scene.MinDeltaTime = 1.0;
  25309. Scene.MaxDeltaTime = 1000.0;
  25310. /** The distance in pixel that you have to move to prevent some events */
  25311. Scene.DragMovementThreshold = 10; // in pixels
  25312. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25313. Scene.LongPressDelay = 500; // in milliseconds
  25314. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25315. Scene.DoubleClickDelay = 300; // in milliseconds
  25316. /** If you need to check double click without raising a single click at first click, enable this flag */
  25317. Scene.ExclusiveDoubleClickMode = false;
  25318. return Scene;
  25319. }());
  25320. BABYLON.Scene = Scene;
  25321. })(BABYLON || (BABYLON = {}));
  25322. //# sourceMappingURL=babylon.scene.js.map
  25323. var BABYLON;
  25324. (function (BABYLON) {
  25325. /**
  25326. * Set of assets to keep when moving a scene into an asset container.
  25327. */
  25328. var KeepAssets = /** @class */ (function () {
  25329. function KeepAssets() {
  25330. /**
  25331. * Cameras to keep.
  25332. */
  25333. this.cameras = new Array();
  25334. /**
  25335. * Lights to keep.
  25336. */
  25337. this.lights = new Array();
  25338. /**
  25339. * Meshes to keep.
  25340. */
  25341. this.meshes = new Array();
  25342. /**
  25343. * Skeletons to keep.
  25344. */
  25345. this.skeletons = new Array();
  25346. /**
  25347. * ParticleSystems to keep.
  25348. */
  25349. this.particleSystems = new Array();
  25350. /**
  25351. * Animations to keep.
  25352. */
  25353. this.animations = new Array();
  25354. /**
  25355. * MultiMaterials to keep.
  25356. */
  25357. this.multiMaterials = new Array();
  25358. /**
  25359. * Materials to keep.
  25360. */
  25361. this.materials = new Array();
  25362. /**
  25363. * MorphTargetManagers to keep.
  25364. */
  25365. this.morphTargetManagers = new Array();
  25366. /**
  25367. * Geometries to keep.
  25368. */
  25369. this.geometries = new Array();
  25370. /**
  25371. * TransformNodes to keep.
  25372. */
  25373. this.transformNodes = new Array();
  25374. /**
  25375. * LensFlareSystems to keep.
  25376. */
  25377. this.lensFlareSystems = new Array();
  25378. /**
  25379. * ShadowGenerators to keep.
  25380. */
  25381. this.shadowGenerators = new Array();
  25382. /**
  25383. * ActionManagers to keep.
  25384. */
  25385. this.actionManagers = new Array();
  25386. /**
  25387. * Sounds to keep.
  25388. */
  25389. this.sounds = new Array();
  25390. }
  25391. return KeepAssets;
  25392. }());
  25393. BABYLON.KeepAssets = KeepAssets;
  25394. /**
  25395. * Container with a set of assets that can be added or removed from a scene.
  25396. */
  25397. var AssetContainer = /** @class */ (function () {
  25398. /**
  25399. * Instantiates an AssetContainer.
  25400. * @param scene The scene the AssetContainer belongs to.
  25401. */
  25402. function AssetContainer(scene) {
  25403. // Objects
  25404. /**
  25405. * Cameras populated in the container.
  25406. */
  25407. this.cameras = new Array();
  25408. /**
  25409. * Lights populated in the container.
  25410. */
  25411. this.lights = new Array();
  25412. /**
  25413. * Meshes populated in the container.
  25414. */
  25415. this.meshes = new Array();
  25416. /**
  25417. * Skeletons populated in the container.
  25418. */
  25419. this.skeletons = new Array();
  25420. /**
  25421. * ParticleSystems populated in the container.
  25422. */
  25423. this.particleSystems = new Array();
  25424. /**
  25425. * Animations populated in the container.
  25426. */
  25427. this.animations = new Array();
  25428. /**
  25429. * MultiMaterials populated in the container.
  25430. */
  25431. this.multiMaterials = new Array();
  25432. /**
  25433. * Materials populated in the container.
  25434. */
  25435. this.materials = new Array();
  25436. /**
  25437. * MorphTargetManagers populated in the container.
  25438. */
  25439. this.morphTargetManagers = new Array();
  25440. /**
  25441. * Geometries populated in the container.
  25442. */
  25443. this.geometries = new Array();
  25444. /**
  25445. * TransformNodes populated in the container.
  25446. */
  25447. this.transformNodes = new Array();
  25448. /**
  25449. * LensFlareSystems populated in the container.
  25450. */
  25451. this.lensFlareSystems = new Array();
  25452. /**
  25453. * ShadowGenerators populated in the container.
  25454. */
  25455. this.shadowGenerators = new Array();
  25456. /**
  25457. * ActionManagers populated in the container.
  25458. */
  25459. this.actionManagers = new Array();
  25460. /**
  25461. * Sounds populated in the container.
  25462. */
  25463. this.sounds = new Array();
  25464. this.scene = scene;
  25465. }
  25466. /**
  25467. * Adds all the assets from the container to the scene.
  25468. */
  25469. AssetContainer.prototype.addAllToScene = function () {
  25470. var _this = this;
  25471. this.cameras.forEach(function (o) {
  25472. _this.scene.addCamera(o);
  25473. });
  25474. this.lights.forEach(function (o) {
  25475. _this.scene.addLight(o);
  25476. });
  25477. this.meshes.forEach(function (o) {
  25478. _this.scene.addMesh(o);
  25479. });
  25480. this.skeletons.forEach(function (o) {
  25481. _this.scene.addSkeleton(o);
  25482. });
  25483. this.particleSystems.forEach(function (o) {
  25484. _this.scene.addParticleSystem(o);
  25485. });
  25486. this.animations.forEach(function (o) {
  25487. _this.scene.addAnimation(o);
  25488. });
  25489. this.multiMaterials.forEach(function (o) {
  25490. _this.scene.addMultiMaterial(o);
  25491. });
  25492. this.materials.forEach(function (o) {
  25493. _this.scene.addMaterial(o);
  25494. });
  25495. this.morphTargetManagers.forEach(function (o) {
  25496. _this.scene.addMorphTargetManager(o);
  25497. });
  25498. this.geometries.forEach(function (o) {
  25499. _this.scene.addGeometry(o);
  25500. });
  25501. this.transformNodes.forEach(function (o) {
  25502. _this.scene.addTransformNode(o);
  25503. });
  25504. this.lensFlareSystems.forEach(function (o) {
  25505. _this.scene.addLensFlareSystem(o);
  25506. });
  25507. this.actionManagers.forEach(function (o) {
  25508. _this.scene.addActionManager(o);
  25509. });
  25510. this.sounds.forEach(function (o) {
  25511. o.play();
  25512. o.autoplay = true;
  25513. _this.scene.mainSoundTrack.AddSound(o);
  25514. });
  25515. };
  25516. /**
  25517. * Removes all the assets in the container from the scene
  25518. */
  25519. AssetContainer.prototype.removeAllFromScene = function () {
  25520. var _this = this;
  25521. this.cameras.forEach(function (o) {
  25522. _this.scene.removeCamera(o);
  25523. });
  25524. this.lights.forEach(function (o) {
  25525. _this.scene.removeLight(o);
  25526. });
  25527. this.meshes.forEach(function (o) {
  25528. _this.scene.removeMesh(o);
  25529. });
  25530. this.skeletons.forEach(function (o) {
  25531. _this.scene.removeSkeleton(o);
  25532. });
  25533. this.particleSystems.forEach(function (o) {
  25534. _this.scene.removeParticleSystem(o);
  25535. });
  25536. this.animations.forEach(function (o) {
  25537. _this.scene.removeAnimation(o);
  25538. });
  25539. this.multiMaterials.forEach(function (o) {
  25540. _this.scene.removeMultiMaterial(o);
  25541. });
  25542. this.materials.forEach(function (o) {
  25543. _this.scene.removeMaterial(o);
  25544. });
  25545. this.morphTargetManagers.forEach(function (o) {
  25546. _this.scene.removeMorphTargetManager(o);
  25547. });
  25548. this.geometries.forEach(function (o) {
  25549. _this.scene.removeGeometry(o);
  25550. });
  25551. this.transformNodes.forEach(function (o) {
  25552. _this.scene.removeTransformNode(o);
  25553. });
  25554. this.lensFlareSystems.forEach(function (o) {
  25555. _this.scene.removeLensFlareSystem(o);
  25556. });
  25557. this.actionManagers.forEach(function (o) {
  25558. _this.scene.removeActionManager(o);
  25559. });
  25560. this.sounds.forEach(function (o) {
  25561. o.stop();
  25562. o.autoplay = false;
  25563. _this.scene.mainSoundTrack.RemoveSound(o);
  25564. });
  25565. };
  25566. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25567. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25568. var asset = sourceAssets_1[_i];
  25569. var move = true;
  25570. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25571. var keepAsset = keepAssets_1[_a];
  25572. if (asset === keepAsset) {
  25573. move = false;
  25574. break;
  25575. }
  25576. }
  25577. if (move) {
  25578. targetAssets.push(asset);
  25579. }
  25580. }
  25581. };
  25582. /**
  25583. * Removes all the assets contained in the scene and adds them to the container.
  25584. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25585. */
  25586. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25587. if (keepAssets === undefined) {
  25588. keepAssets = new KeepAssets();
  25589. }
  25590. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25591. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25592. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25593. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25594. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25595. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25596. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25597. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25598. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25599. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25600. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25601. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25602. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25603. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25604. this.removeAllFromScene();
  25605. };
  25606. return AssetContainer;
  25607. }());
  25608. BABYLON.AssetContainer = AssetContainer;
  25609. })(BABYLON || (BABYLON = {}));
  25610. //# sourceMappingURL=babylon.assetContainer.js.map
  25611. var BABYLON;
  25612. (function (BABYLON) {
  25613. var Buffer = /** @class */ (function () {
  25614. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25615. if (instanced === void 0) { instanced = false; }
  25616. if (engine instanceof BABYLON.Mesh) {
  25617. this._engine = engine.getScene().getEngine();
  25618. }
  25619. else {
  25620. this._engine = engine;
  25621. }
  25622. this._updatable = updatable;
  25623. this._instanced = instanced;
  25624. this._data = data;
  25625. this._strideSize = stride;
  25626. if (!postponeInternalCreation) {
  25627. this.create();
  25628. }
  25629. }
  25630. /**
  25631. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25632. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25633. * @param offset defines offset in the buffer (0 by default)
  25634. * @param size defines the size in floats of attributes (position is 3 for instance)
  25635. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25636. * @param instanced defines if the vertex buffer contains indexed data
  25637. * @returns the new vertex buffer
  25638. */
  25639. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25640. // a lot of these parameters are ignored as they are overriden by the buffer
  25641. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25642. };
  25643. // Properties
  25644. Buffer.prototype.isUpdatable = function () {
  25645. return this._updatable;
  25646. };
  25647. Buffer.prototype.getData = function () {
  25648. return this._data;
  25649. };
  25650. Buffer.prototype.getBuffer = function () {
  25651. return this._buffer;
  25652. };
  25653. Buffer.prototype.getStrideSize = function () {
  25654. return this._strideSize;
  25655. };
  25656. // public getIsInstanced(): boolean {
  25657. // return this._instanced;
  25658. // }
  25659. // public get instanceDivisor(): number {
  25660. // return this._instanceDivisor;
  25661. // }
  25662. // public set instanceDivisor(value: number) {
  25663. // this._instanceDivisor = value;
  25664. // if (value == 0) {
  25665. // this._instanced = false;
  25666. // } else {
  25667. // this._instanced = true;
  25668. // }
  25669. // }
  25670. // Methods
  25671. Buffer.prototype.create = function (data) {
  25672. if (data === void 0) { data = null; }
  25673. if (!data && this._buffer) {
  25674. return; // nothing to do
  25675. }
  25676. data = data || this._data;
  25677. if (!data) {
  25678. return;
  25679. }
  25680. if (!this._buffer) {
  25681. if (this._updatable) {
  25682. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25683. this._data = data;
  25684. }
  25685. else {
  25686. this._buffer = this._engine.createVertexBuffer(data);
  25687. }
  25688. }
  25689. else if (this._updatable) {
  25690. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25691. this._data = data;
  25692. }
  25693. };
  25694. Buffer.prototype._rebuild = function () {
  25695. this._buffer = null;
  25696. this.create(this._data);
  25697. };
  25698. Buffer.prototype.update = function (data) {
  25699. this.create(data);
  25700. };
  25701. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25702. if (!this._buffer) {
  25703. return;
  25704. }
  25705. if (this._updatable) {
  25706. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25707. this._data = null;
  25708. }
  25709. };
  25710. Buffer.prototype.dispose = function () {
  25711. if (!this._buffer) {
  25712. return;
  25713. }
  25714. if (this._engine._releaseBuffer(this._buffer)) {
  25715. this._buffer = null;
  25716. }
  25717. };
  25718. return Buffer;
  25719. }());
  25720. BABYLON.Buffer = Buffer;
  25721. })(BABYLON || (BABYLON = {}));
  25722. //# sourceMappingURL=babylon.buffer.js.map
  25723. var BABYLON;
  25724. (function (BABYLON) {
  25725. var VertexBuffer = /** @class */ (function () {
  25726. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25727. if (data instanceof BABYLON.Buffer) {
  25728. if (!stride) {
  25729. stride = data.getStrideSize();
  25730. }
  25731. this._buffer = data;
  25732. this._ownsBuffer = false;
  25733. }
  25734. else {
  25735. if (!stride) {
  25736. stride = VertexBuffer.DeduceStride(kind);
  25737. }
  25738. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25739. this._ownsBuffer = true;
  25740. }
  25741. this._stride = stride;
  25742. this._instanced = instanced !== undefined ? instanced : false;
  25743. this._instanceDivisor = instanced ? 1 : 0;
  25744. this._offset = offset ? offset : 0;
  25745. this._size = size ? size : stride;
  25746. this._kind = kind;
  25747. }
  25748. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25749. /**
  25750. * Gets or sets the instance divisor when in instanced mode
  25751. */
  25752. get: function () {
  25753. return this._instanceDivisor;
  25754. },
  25755. set: function (value) {
  25756. this._instanceDivisor = value;
  25757. if (value == 0) {
  25758. this._instanced = false;
  25759. }
  25760. else {
  25761. this._instanced = true;
  25762. }
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. VertexBuffer.prototype._rebuild = function () {
  25768. if (!this._buffer) {
  25769. return;
  25770. }
  25771. this._buffer._rebuild();
  25772. };
  25773. /**
  25774. * Returns the kind of the VertexBuffer (string).
  25775. */
  25776. VertexBuffer.prototype.getKind = function () {
  25777. return this._kind;
  25778. };
  25779. // Properties
  25780. /**
  25781. * Boolean : is the VertexBuffer updatable ?
  25782. */
  25783. VertexBuffer.prototype.isUpdatable = function () {
  25784. return this._buffer.isUpdatable();
  25785. };
  25786. /**
  25787. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25788. */
  25789. VertexBuffer.prototype.getData = function () {
  25790. return this._buffer.getData();
  25791. };
  25792. /**
  25793. * Returns the WebGLBuffer associated to the VertexBuffer.
  25794. */
  25795. VertexBuffer.prototype.getBuffer = function () {
  25796. return this._buffer.getBuffer();
  25797. };
  25798. /**
  25799. * Returns the stride of the VertexBuffer (integer).
  25800. */
  25801. VertexBuffer.prototype.getStrideSize = function () {
  25802. return this._stride;
  25803. };
  25804. /**
  25805. * Returns the offset (integer).
  25806. */
  25807. VertexBuffer.prototype.getOffset = function () {
  25808. return this._offset;
  25809. };
  25810. /**
  25811. * Returns the VertexBuffer total size (integer).
  25812. */
  25813. VertexBuffer.prototype.getSize = function () {
  25814. return this._size;
  25815. };
  25816. /**
  25817. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25818. */
  25819. VertexBuffer.prototype.getIsInstanced = function () {
  25820. return this._instanced;
  25821. };
  25822. /**
  25823. * Returns the instancing divisor, zero for non-instanced (integer).
  25824. */
  25825. VertexBuffer.prototype.getInstanceDivisor = function () {
  25826. return this._instanceDivisor;
  25827. };
  25828. // Methods
  25829. /**
  25830. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25831. * Returns the created WebGLBuffer.
  25832. */
  25833. VertexBuffer.prototype.create = function (data) {
  25834. return this._buffer.create(data);
  25835. };
  25836. /**
  25837. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25838. * This function will create a new buffer if the current one is not updatable
  25839. * Returns the updated WebGLBuffer.
  25840. */
  25841. VertexBuffer.prototype.update = function (data) {
  25842. return this._buffer.update(data);
  25843. };
  25844. /**
  25845. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25846. * Returns the directly updated WebGLBuffer.
  25847. */
  25848. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25849. return this._buffer.updateDirectly(data, offset);
  25850. };
  25851. /**
  25852. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25853. */
  25854. VertexBuffer.prototype.dispose = function () {
  25855. if (this._ownsBuffer) {
  25856. this._buffer.dispose();
  25857. }
  25858. };
  25859. Object.defineProperty(VertexBuffer, "PositionKind", {
  25860. get: function () {
  25861. return VertexBuffer._PositionKind;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(VertexBuffer, "NormalKind", {
  25867. get: function () {
  25868. return VertexBuffer._NormalKind;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(VertexBuffer, "TangentKind", {
  25874. get: function () {
  25875. return VertexBuffer._TangentKind;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(VertexBuffer, "UVKind", {
  25881. get: function () {
  25882. return VertexBuffer._UVKind;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25888. get: function () {
  25889. return VertexBuffer._UV2Kind;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25895. get: function () {
  25896. return VertexBuffer._UV3Kind;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25902. get: function () {
  25903. return VertexBuffer._UV4Kind;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25909. get: function () {
  25910. return VertexBuffer._UV5Kind;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25916. get: function () {
  25917. return VertexBuffer._UV6Kind;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(VertexBuffer, "ColorKind", {
  25923. get: function () {
  25924. return VertexBuffer._ColorKind;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25930. get: function () {
  25931. return VertexBuffer._MatricesIndicesKind;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25937. get: function () {
  25938. return VertexBuffer._MatricesWeightsKind;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25944. get: function () {
  25945. return VertexBuffer._MatricesIndicesExtraKind;
  25946. },
  25947. enumerable: true,
  25948. configurable: true
  25949. });
  25950. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25951. get: function () {
  25952. return VertexBuffer._MatricesWeightsExtraKind;
  25953. },
  25954. enumerable: true,
  25955. configurable: true
  25956. });
  25957. /**
  25958. * Deduces the stride given a kind.
  25959. * @param kind The kind string to deduce
  25960. * @returns The deduced stride
  25961. */
  25962. VertexBuffer.DeduceStride = function (kind) {
  25963. switch (kind) {
  25964. case VertexBuffer.UVKind:
  25965. case VertexBuffer.UV2Kind:
  25966. case VertexBuffer.UV3Kind:
  25967. case VertexBuffer.UV4Kind:
  25968. case VertexBuffer.UV5Kind:
  25969. case VertexBuffer.UV6Kind:
  25970. return 2;
  25971. case VertexBuffer.NormalKind:
  25972. case VertexBuffer.PositionKind:
  25973. return 3;
  25974. case VertexBuffer.ColorKind:
  25975. case VertexBuffer.MatricesIndicesKind:
  25976. case VertexBuffer.MatricesIndicesExtraKind:
  25977. case VertexBuffer.MatricesWeightsKind:
  25978. case VertexBuffer.MatricesWeightsExtraKind:
  25979. case VertexBuffer.TangentKind:
  25980. return 4;
  25981. default:
  25982. throw new Error("Invalid kind '" + kind + "'");
  25983. }
  25984. };
  25985. // Enums
  25986. VertexBuffer._PositionKind = "position";
  25987. VertexBuffer._NormalKind = "normal";
  25988. VertexBuffer._TangentKind = "tangent";
  25989. VertexBuffer._UVKind = "uv";
  25990. VertexBuffer._UV2Kind = "uv2";
  25991. VertexBuffer._UV3Kind = "uv3";
  25992. VertexBuffer._UV4Kind = "uv4";
  25993. VertexBuffer._UV5Kind = "uv5";
  25994. VertexBuffer._UV6Kind = "uv6";
  25995. VertexBuffer._ColorKind = "color";
  25996. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25997. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25998. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25999. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26000. return VertexBuffer;
  26001. }());
  26002. BABYLON.VertexBuffer = VertexBuffer;
  26003. })(BABYLON || (BABYLON = {}));
  26004. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26005. var BABYLON;
  26006. (function (BABYLON) {
  26007. /**
  26008. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26009. */
  26010. var DummyInternalTextureTracker = /** @class */ (function () {
  26011. function DummyInternalTextureTracker() {
  26012. /**
  26013. * Gets or set the previous tracker in the list
  26014. */
  26015. this.previous = null;
  26016. /**
  26017. * Gets or set the next tracker in the list
  26018. */
  26019. this.next = null;
  26020. }
  26021. return DummyInternalTextureTracker;
  26022. }());
  26023. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26024. })(BABYLON || (BABYLON = {}));
  26025. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26026. var BABYLON;
  26027. (function (BABYLON) {
  26028. /**
  26029. * Class used to store data associated with WebGL texture data for the engine
  26030. * This class should not be used directly
  26031. */
  26032. var InternalTexture = /** @class */ (function () {
  26033. /**
  26034. * Creates a new InternalTexture
  26035. * @param engine defines the engine to use
  26036. * @param dataSource defines the type of data that will be used
  26037. */
  26038. function InternalTexture(engine, dataSource) {
  26039. /**
  26040. * Observable called when the texture is loaded
  26041. */
  26042. this.onLoadedObservable = new BABYLON.Observable();
  26043. /**
  26044. * Gets or set the previous tracker in the list
  26045. */
  26046. this.previous = null;
  26047. /**
  26048. * Gets or set the next tracker in the list
  26049. */
  26050. this.next = null;
  26051. // Private
  26052. /** @ignore */
  26053. this._initialSlot = -1;
  26054. /** @ignore */
  26055. this._designatedSlot = -1;
  26056. /** @ignore */
  26057. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26058. /** @ignore */
  26059. this._comparisonFunction = 0;
  26060. /** @ignore */
  26061. this._references = 1;
  26062. this._engine = engine;
  26063. this._dataSource = dataSource;
  26064. this._webGLTexture = engine._createTexture();
  26065. }
  26066. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26067. /**
  26068. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26069. */
  26070. get: function () {
  26071. return this._dataSource;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. /**
  26077. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26078. */
  26079. InternalTexture.prototype.incrementReferences = function () {
  26080. this._references++;
  26081. };
  26082. /**
  26083. * Change the size of the texture (not the size of the content)
  26084. * @param width defines the new width
  26085. * @param height defines the new height
  26086. * @param depth defines the new depth (1 by default)
  26087. */
  26088. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26089. if (depth === void 0) { depth = 1; }
  26090. this.width = width;
  26091. this.height = height;
  26092. this.depth = depth;
  26093. this.baseWidth = width;
  26094. this.baseHeight = height;
  26095. this.baseDepth = depth;
  26096. this._size = width * height * depth;
  26097. };
  26098. /** @ignore */
  26099. InternalTexture.prototype._rebuild = function () {
  26100. var _this = this;
  26101. var proxy;
  26102. this.isReady = false;
  26103. this._cachedCoordinatesMode = null;
  26104. this._cachedWrapU = null;
  26105. this._cachedWrapV = null;
  26106. this._cachedAnisotropicFilteringLevel = null;
  26107. switch (this._dataSource) {
  26108. case InternalTexture.DATASOURCE_TEMP:
  26109. return;
  26110. case InternalTexture.DATASOURCE_URL:
  26111. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26112. _this.isReady = true;
  26113. }, null, this._buffer, undefined, this.format);
  26114. proxy._swapAndDie(this);
  26115. return;
  26116. case InternalTexture.DATASOURCE_RAW:
  26117. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26118. proxy._swapAndDie(this);
  26119. this.isReady = true;
  26120. return;
  26121. case InternalTexture.DATASOURCE_RAW3D:
  26122. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26123. proxy._swapAndDie(this);
  26124. this.isReady = true;
  26125. return;
  26126. case InternalTexture.DATASOURCE_DYNAMIC:
  26127. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26128. proxy._swapAndDie(this);
  26129. // The engine will make sure to update content so no need to flag it as isReady = true
  26130. return;
  26131. case InternalTexture.DATASOURCE_RENDERTARGET:
  26132. var options = new BABYLON.RenderTargetCreationOptions();
  26133. options.generateDepthBuffer = this._generateDepthBuffer;
  26134. options.generateMipMaps = this.generateMipMaps;
  26135. options.generateStencilBuffer = this._generateStencilBuffer;
  26136. options.samplingMode = this.samplingMode;
  26137. options.type = this.type;
  26138. if (this.isCube) {
  26139. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26140. }
  26141. else {
  26142. var size = {
  26143. width: this.width,
  26144. height: this.height
  26145. };
  26146. proxy = this._engine.createRenderTargetTexture(size, options);
  26147. }
  26148. proxy._swapAndDie(this);
  26149. this.isReady = true;
  26150. return;
  26151. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26152. var depthTextureOptions = {
  26153. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26154. comparisonFunction: this._comparisonFunction,
  26155. generateStencil: this._generateStencilBuffer,
  26156. };
  26157. if (this.isCube) {
  26158. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26159. }
  26160. else {
  26161. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26162. }
  26163. proxy._swapAndDie(this);
  26164. this.isReady = true;
  26165. return;
  26166. case InternalTexture.DATASOURCE_CUBE:
  26167. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26168. _this.isReady = true;
  26169. }, null, this.format, this._extension);
  26170. proxy._swapAndDie(this);
  26171. return;
  26172. case InternalTexture.DATASOURCE_CUBERAW:
  26173. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26174. proxy._swapAndDie(this);
  26175. this.isReady = true;
  26176. return;
  26177. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26178. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26179. if (proxy) {
  26180. proxy._swapAndDie(_this);
  26181. }
  26182. _this.isReady = true;
  26183. }, null, this.format, this._extension);
  26184. return;
  26185. }
  26186. };
  26187. InternalTexture.prototype._swapAndDie = function (target) {
  26188. target._webGLTexture = this._webGLTexture;
  26189. if (this._framebuffer) {
  26190. target._framebuffer = this._framebuffer;
  26191. }
  26192. if (this._depthStencilBuffer) {
  26193. target._depthStencilBuffer = this._depthStencilBuffer;
  26194. }
  26195. if (this._lodTextureHigh) {
  26196. if (target._lodTextureHigh) {
  26197. target._lodTextureHigh.dispose();
  26198. }
  26199. target._lodTextureHigh = this._lodTextureHigh;
  26200. }
  26201. if (this._lodTextureMid) {
  26202. if (target._lodTextureMid) {
  26203. target._lodTextureMid.dispose();
  26204. }
  26205. target._lodTextureMid = this._lodTextureMid;
  26206. }
  26207. if (this._lodTextureLow) {
  26208. if (target._lodTextureLow) {
  26209. target._lodTextureLow.dispose();
  26210. }
  26211. target._lodTextureLow = this._lodTextureLow;
  26212. }
  26213. var cache = this._engine.getLoadedTexturesCache();
  26214. var index = cache.indexOf(this);
  26215. if (index !== -1) {
  26216. cache.splice(index, 1);
  26217. }
  26218. };
  26219. /**
  26220. * Dispose the current allocated resources
  26221. */
  26222. InternalTexture.prototype.dispose = function () {
  26223. if (!this._webGLTexture) {
  26224. return;
  26225. }
  26226. this._references--;
  26227. if (this._references === 0) {
  26228. this._engine._releaseTexture(this);
  26229. this._webGLTexture = null;
  26230. this.previous = null;
  26231. this.next = null;
  26232. }
  26233. };
  26234. /**
  26235. * The source of the texture data is unknown
  26236. */
  26237. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26238. /**
  26239. * Texture data comes from an URL
  26240. */
  26241. InternalTexture.DATASOURCE_URL = 1;
  26242. /**
  26243. * Texture data is only used for temporary storage
  26244. */
  26245. InternalTexture.DATASOURCE_TEMP = 2;
  26246. /**
  26247. * Texture data comes from raw data (ArrayBuffer)
  26248. */
  26249. InternalTexture.DATASOURCE_RAW = 3;
  26250. /**
  26251. * Texture content is dynamic (video or dynamic texture)
  26252. */
  26253. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26254. /**
  26255. * Texture content is generated by rendering to it
  26256. */
  26257. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26258. /**
  26259. * Texture content is part of a multi render target process
  26260. */
  26261. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26262. /**
  26263. * Texture data comes from a cube data file
  26264. */
  26265. InternalTexture.DATASOURCE_CUBE = 7;
  26266. /**
  26267. * Texture data comes from a raw cube data
  26268. */
  26269. InternalTexture.DATASOURCE_CUBERAW = 8;
  26270. /**
  26271. * Texture data come from a prefiltered cube data file
  26272. */
  26273. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26274. /**
  26275. * Texture content is raw 3D data
  26276. */
  26277. InternalTexture.DATASOURCE_RAW3D = 10;
  26278. /**
  26279. * Texture content is a depth texture
  26280. */
  26281. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26282. return InternalTexture;
  26283. }());
  26284. BABYLON.InternalTexture = InternalTexture;
  26285. })(BABYLON || (BABYLON = {}));
  26286. //# sourceMappingURL=babylon.internalTexture.js.map
  26287. var BABYLON;
  26288. (function (BABYLON) {
  26289. var BaseTexture = /** @class */ (function () {
  26290. function BaseTexture(scene) {
  26291. this._hasAlpha = false;
  26292. this.getAlphaFromRGB = false;
  26293. this.level = 1;
  26294. this.coordinatesIndex = 0;
  26295. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26296. /**
  26297. * | Value | Type | Description |
  26298. * | ----- | ------------------ | ----------- |
  26299. * | 0 | CLAMP_ADDRESSMODE | |
  26300. * | 1 | WRAP_ADDRESSMODE | |
  26301. * | 2 | MIRROR_ADDRESSMODE | |
  26302. */
  26303. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26304. /**
  26305. * | Value | Type | Description |
  26306. * | ----- | ------------------ | ----------- |
  26307. * | 0 | CLAMP_ADDRESSMODE | |
  26308. * | 1 | WRAP_ADDRESSMODE | |
  26309. * | 2 | MIRROR_ADDRESSMODE | |
  26310. */
  26311. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26312. /**
  26313. * | Value | Type | Description |
  26314. * | ----- | ------------------ | ----------- |
  26315. * | 0 | CLAMP_ADDRESSMODE | |
  26316. * | 1 | WRAP_ADDRESSMODE | |
  26317. * | 2 | MIRROR_ADDRESSMODE | |
  26318. */
  26319. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26320. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26321. this.isCube = false;
  26322. this.is3D = false;
  26323. this.gammaSpace = true;
  26324. this.invertZ = false;
  26325. this.lodLevelInAlpha = false;
  26326. this.lodGenerationOffset = 0.0;
  26327. this.lodGenerationScale = 0.8;
  26328. this.isRenderTarget = false;
  26329. this.animations = new Array();
  26330. /**
  26331. * An event triggered when the texture is disposed.
  26332. * @type {BABYLON.Observable}
  26333. */
  26334. this.onDisposeObservable = new BABYLON.Observable();
  26335. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26336. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26337. if (this._scene) {
  26338. this._scene.textures.push(this);
  26339. }
  26340. this._uid = null;
  26341. }
  26342. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26343. get: function () {
  26344. return this._hasAlpha;
  26345. },
  26346. set: function (value) {
  26347. if (this._hasAlpha === value) {
  26348. return;
  26349. }
  26350. this._hasAlpha = value;
  26351. if (this._scene) {
  26352. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26353. }
  26354. },
  26355. enumerable: true,
  26356. configurable: true
  26357. });
  26358. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26359. get: function () {
  26360. return this._coordinatesMode;
  26361. },
  26362. /**
  26363. * How a texture is mapped.
  26364. *
  26365. * | Value | Type | Description |
  26366. * | ----- | ----------------------------------- | ----------- |
  26367. * | 0 | EXPLICIT_MODE | |
  26368. * | 1 | SPHERICAL_MODE | |
  26369. * | 2 | PLANAR_MODE | |
  26370. * | 3 | CUBIC_MODE | |
  26371. * | 4 | PROJECTION_MODE | |
  26372. * | 5 | SKYBOX_MODE | |
  26373. * | 6 | INVCUBIC_MODE | |
  26374. * | 7 | EQUIRECTANGULAR_MODE | |
  26375. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26376. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26377. */
  26378. set: function (value) {
  26379. if (this._coordinatesMode === value) {
  26380. return;
  26381. }
  26382. this._coordinatesMode = value;
  26383. if (this._scene) {
  26384. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26385. }
  26386. },
  26387. enumerable: true,
  26388. configurable: true
  26389. });
  26390. Object.defineProperty(BaseTexture.prototype, "uid", {
  26391. get: function () {
  26392. if (!this._uid) {
  26393. this._uid = BABYLON.Tools.RandomId();
  26394. }
  26395. return this._uid;
  26396. },
  26397. enumerable: true,
  26398. configurable: true
  26399. });
  26400. BaseTexture.prototype.toString = function () {
  26401. return this.name;
  26402. };
  26403. BaseTexture.prototype.getClassName = function () {
  26404. return "BaseTexture";
  26405. };
  26406. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26407. set: function (callback) {
  26408. if (this._onDisposeObserver) {
  26409. this.onDisposeObservable.remove(this._onDisposeObserver);
  26410. }
  26411. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26417. get: function () {
  26418. return true;
  26419. },
  26420. enumerable: true,
  26421. configurable: true
  26422. });
  26423. BaseTexture.prototype.getScene = function () {
  26424. return this._scene;
  26425. };
  26426. BaseTexture.prototype.getTextureMatrix = function () {
  26427. return BABYLON.Matrix.IdentityReadOnly;
  26428. };
  26429. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26430. return BABYLON.Matrix.IdentityReadOnly;
  26431. };
  26432. BaseTexture.prototype.getInternalTexture = function () {
  26433. return this._texture;
  26434. };
  26435. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26436. return !this.isBlocking || this.isReady();
  26437. };
  26438. BaseTexture.prototype.isReady = function () {
  26439. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26440. this.delayLoad();
  26441. return false;
  26442. }
  26443. if (this._texture) {
  26444. return this._texture.isReady;
  26445. }
  26446. return false;
  26447. };
  26448. BaseTexture.prototype.getSize = function () {
  26449. if (this._texture && this._texture.width) {
  26450. return new BABYLON.Size(this._texture.width, this._texture.height);
  26451. }
  26452. if (this._texture && this._texture._size) {
  26453. return new BABYLON.Size(this._texture._size, this._texture._size);
  26454. }
  26455. return BABYLON.Size.Zero();
  26456. };
  26457. BaseTexture.prototype.getBaseSize = function () {
  26458. if (!this.isReady() || !this._texture)
  26459. return BABYLON.Size.Zero();
  26460. if (this._texture._size) {
  26461. return new BABYLON.Size(this._texture._size, this._texture._size);
  26462. }
  26463. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26464. };
  26465. BaseTexture.prototype.scale = function (ratio) {
  26466. };
  26467. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26468. get: function () {
  26469. return false;
  26470. },
  26471. enumerable: true,
  26472. configurable: true
  26473. });
  26474. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26475. if (!this._scene) {
  26476. return null;
  26477. }
  26478. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26479. for (var index = 0; index < texturesCache.length; index++) {
  26480. var texturesCacheEntry = texturesCache[index];
  26481. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26482. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26483. texturesCacheEntry.incrementReferences();
  26484. return texturesCacheEntry;
  26485. }
  26486. }
  26487. }
  26488. return null;
  26489. };
  26490. BaseTexture.prototype._rebuild = function () {
  26491. };
  26492. BaseTexture.prototype.delayLoad = function () {
  26493. };
  26494. BaseTexture.prototype.clone = function () {
  26495. return null;
  26496. };
  26497. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26498. get: function () {
  26499. if (!this._texture) {
  26500. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26501. }
  26502. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26503. },
  26504. enumerable: true,
  26505. configurable: true
  26506. });
  26507. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26508. get: function () {
  26509. if (!this._texture) {
  26510. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26511. }
  26512. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26513. },
  26514. enumerable: true,
  26515. configurable: true
  26516. });
  26517. BaseTexture.prototype.readPixels = function (faceIndex) {
  26518. if (faceIndex === void 0) { faceIndex = 0; }
  26519. if (!this._texture) {
  26520. return null;
  26521. }
  26522. var size = this.getSize();
  26523. var scene = this.getScene();
  26524. if (!scene) {
  26525. return null;
  26526. }
  26527. var engine = scene.getEngine();
  26528. if (this._texture.isCube) {
  26529. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26530. }
  26531. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26532. };
  26533. BaseTexture.prototype.releaseInternalTexture = function () {
  26534. if (this._texture) {
  26535. this._texture.dispose();
  26536. this._texture = null;
  26537. }
  26538. };
  26539. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26540. get: function () {
  26541. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26542. return null;
  26543. }
  26544. if (!this._texture._sphericalPolynomial) {
  26545. this._texture._sphericalPolynomial =
  26546. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26547. }
  26548. return this._texture._sphericalPolynomial;
  26549. },
  26550. set: function (value) {
  26551. if (this._texture) {
  26552. this._texture._sphericalPolynomial = value;
  26553. }
  26554. },
  26555. enumerable: true,
  26556. configurable: true
  26557. });
  26558. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26559. get: function () {
  26560. if (this._texture) {
  26561. return this._texture._lodTextureHigh;
  26562. }
  26563. return null;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26569. get: function () {
  26570. if (this._texture) {
  26571. return this._texture._lodTextureMid;
  26572. }
  26573. return null;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26579. get: function () {
  26580. if (this._texture) {
  26581. return this._texture._lodTextureLow;
  26582. }
  26583. return null;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. BaseTexture.prototype.dispose = function () {
  26589. if (!this._scene) {
  26590. return;
  26591. }
  26592. // Animations
  26593. this._scene.stopAnimation(this);
  26594. // Remove from scene
  26595. this._scene._removePendingData(this);
  26596. var index = this._scene.textures.indexOf(this);
  26597. if (index >= 0) {
  26598. this._scene.textures.splice(index, 1);
  26599. }
  26600. if (this._texture === undefined) {
  26601. return;
  26602. }
  26603. // Release
  26604. this.releaseInternalTexture();
  26605. // Callback
  26606. this.onDisposeObservable.notifyObservers(this);
  26607. this.onDisposeObservable.clear();
  26608. };
  26609. BaseTexture.prototype.serialize = function () {
  26610. if (!this.name) {
  26611. return null;
  26612. }
  26613. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26614. // Animations
  26615. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26616. return serializationObject;
  26617. };
  26618. BaseTexture.WhenAllReady = function (textures, callback) {
  26619. var numRemaining = textures.length;
  26620. if (numRemaining === 0) {
  26621. callback();
  26622. return;
  26623. }
  26624. var _loop_1 = function () {
  26625. texture = textures[i];
  26626. if (texture.isReady()) {
  26627. if (--numRemaining === 0) {
  26628. callback();
  26629. }
  26630. }
  26631. else {
  26632. onLoadObservable = texture.onLoadObservable;
  26633. var onLoadCallback_1 = function () {
  26634. onLoadObservable.removeCallback(onLoadCallback_1);
  26635. if (--numRemaining === 0) {
  26636. callback();
  26637. }
  26638. };
  26639. onLoadObservable.add(onLoadCallback_1);
  26640. }
  26641. };
  26642. var texture, onLoadObservable;
  26643. for (var i = 0; i < textures.length; i++) {
  26644. _loop_1();
  26645. }
  26646. };
  26647. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26648. __decorate([
  26649. BABYLON.serialize()
  26650. ], BaseTexture.prototype, "name", void 0);
  26651. __decorate([
  26652. BABYLON.serialize("hasAlpha")
  26653. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26654. __decorate([
  26655. BABYLON.serialize()
  26656. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26657. __decorate([
  26658. BABYLON.serialize()
  26659. ], BaseTexture.prototype, "level", void 0);
  26660. __decorate([
  26661. BABYLON.serialize()
  26662. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26663. __decorate([
  26664. BABYLON.serialize("coordinatesMode")
  26665. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26666. __decorate([
  26667. BABYLON.serialize()
  26668. ], BaseTexture.prototype, "wrapU", void 0);
  26669. __decorate([
  26670. BABYLON.serialize()
  26671. ], BaseTexture.prototype, "wrapV", void 0);
  26672. __decorate([
  26673. BABYLON.serialize()
  26674. ], BaseTexture.prototype, "wrapR", void 0);
  26675. __decorate([
  26676. BABYLON.serialize()
  26677. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26678. __decorate([
  26679. BABYLON.serialize()
  26680. ], BaseTexture.prototype, "isCube", void 0);
  26681. __decorate([
  26682. BABYLON.serialize()
  26683. ], BaseTexture.prototype, "is3D", void 0);
  26684. __decorate([
  26685. BABYLON.serialize()
  26686. ], BaseTexture.prototype, "gammaSpace", void 0);
  26687. __decorate([
  26688. BABYLON.serialize()
  26689. ], BaseTexture.prototype, "invertZ", void 0);
  26690. __decorate([
  26691. BABYLON.serialize()
  26692. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26693. __decorate([
  26694. BABYLON.serialize()
  26695. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26696. __decorate([
  26697. BABYLON.serialize()
  26698. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26699. __decorate([
  26700. BABYLON.serialize()
  26701. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26702. return BaseTexture;
  26703. }());
  26704. BABYLON.BaseTexture = BaseTexture;
  26705. })(BABYLON || (BABYLON = {}));
  26706. //# sourceMappingURL=babylon.baseTexture.js.map
  26707. var BABYLON;
  26708. (function (BABYLON) {
  26709. var Texture = /** @class */ (function (_super) {
  26710. __extends(Texture, _super);
  26711. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26712. if (noMipmap === void 0) { noMipmap = false; }
  26713. if (invertY === void 0) { invertY = true; }
  26714. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26715. if (onLoad === void 0) { onLoad = null; }
  26716. if (onError === void 0) { onError = null; }
  26717. if (buffer === void 0) { buffer = null; }
  26718. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26719. var _this = _super.call(this, scene) || this;
  26720. _this.uOffset = 0;
  26721. _this.vOffset = 0;
  26722. _this.uScale = 1.0;
  26723. _this.vScale = 1.0;
  26724. _this.uAng = 0;
  26725. _this.vAng = 0;
  26726. _this.wAng = 0;
  26727. _this._isBlocking = true;
  26728. _this.name = url || "";
  26729. _this.url = url;
  26730. _this._noMipmap = noMipmap;
  26731. _this._invertY = invertY;
  26732. _this._samplingMode = samplingMode;
  26733. _this._buffer = buffer;
  26734. _this._deleteBuffer = deleteBuffer;
  26735. if (format) {
  26736. _this._format = format;
  26737. }
  26738. scene = _this.getScene();
  26739. if (!scene) {
  26740. return _this;
  26741. }
  26742. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26743. var load = function () {
  26744. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26745. _this.onLoadObservable.notifyObservers(_this);
  26746. }
  26747. if (onLoad) {
  26748. onLoad();
  26749. }
  26750. if (!_this.isBlocking && scene) {
  26751. scene.resetCachedMaterial();
  26752. }
  26753. };
  26754. if (!_this.url) {
  26755. _this._delayedOnLoad = load;
  26756. _this._delayedOnError = onError;
  26757. return _this;
  26758. }
  26759. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26760. if (!_this._texture) {
  26761. if (!scene.useDelayedTextureLoading) {
  26762. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26763. if (deleteBuffer) {
  26764. delete _this._buffer;
  26765. }
  26766. }
  26767. else {
  26768. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26769. _this._delayedOnLoad = load;
  26770. _this._delayedOnError = onError;
  26771. }
  26772. }
  26773. else {
  26774. if (_this._texture.isReady) {
  26775. BABYLON.Tools.SetImmediate(function () { return load(); });
  26776. }
  26777. else {
  26778. _this._texture.onLoadedObservable.add(load);
  26779. }
  26780. }
  26781. return _this;
  26782. }
  26783. Object.defineProperty(Texture.prototype, "noMipmap", {
  26784. get: function () {
  26785. return this._noMipmap;
  26786. },
  26787. enumerable: true,
  26788. configurable: true
  26789. });
  26790. Object.defineProperty(Texture.prototype, "isBlocking", {
  26791. get: function () {
  26792. return this._isBlocking;
  26793. },
  26794. set: function (value) {
  26795. this._isBlocking = value;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. Object.defineProperty(Texture.prototype, "samplingMode", {
  26801. get: function () {
  26802. return this._samplingMode;
  26803. },
  26804. enumerable: true,
  26805. configurable: true
  26806. });
  26807. Texture.prototype.updateURL = function (url) {
  26808. this.url = url;
  26809. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26810. this.delayLoad();
  26811. };
  26812. Texture.prototype.delayLoad = function () {
  26813. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26814. return;
  26815. }
  26816. var scene = this.getScene();
  26817. if (!scene) {
  26818. return;
  26819. }
  26820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26821. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26822. if (!this._texture) {
  26823. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26824. if (this._deleteBuffer) {
  26825. delete this._buffer;
  26826. }
  26827. }
  26828. else {
  26829. if (this._delayedOnLoad) {
  26830. if (this._texture.isReady) {
  26831. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26832. }
  26833. else {
  26834. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26835. }
  26836. }
  26837. }
  26838. this._delayedOnLoad = null;
  26839. this._delayedOnError = null;
  26840. };
  26841. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26842. if (!this._texture) {
  26843. return;
  26844. }
  26845. var scene = this.getScene();
  26846. if (!scene) {
  26847. return;
  26848. }
  26849. this._samplingMode = samplingMode;
  26850. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26851. };
  26852. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26853. x *= this.uScale;
  26854. y *= this.vScale;
  26855. x -= 0.5 * this.uScale;
  26856. y -= 0.5 * this.vScale;
  26857. z -= 0.5;
  26858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26859. t.x += 0.5 * this.uScale + this.uOffset;
  26860. t.y += 0.5 * this.vScale + this.vOffset;
  26861. t.z += 0.5;
  26862. };
  26863. Texture.prototype.getTextureMatrix = function () {
  26864. var _this = this;
  26865. if (this.uOffset === this._cachedUOffset &&
  26866. this.vOffset === this._cachedVOffset &&
  26867. this.uScale === this._cachedUScale &&
  26868. this.vScale === this._cachedVScale &&
  26869. this.uAng === this._cachedUAng &&
  26870. this.vAng === this._cachedVAng &&
  26871. this.wAng === this._cachedWAng) {
  26872. return this._cachedTextureMatrix;
  26873. }
  26874. this._cachedUOffset = this.uOffset;
  26875. this._cachedVOffset = this.vOffset;
  26876. this._cachedUScale = this.uScale;
  26877. this._cachedVScale = this.vScale;
  26878. this._cachedUAng = this.uAng;
  26879. this._cachedVAng = this.vAng;
  26880. this._cachedWAng = this.wAng;
  26881. if (!this._cachedTextureMatrix) {
  26882. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26883. this._rowGenerationMatrix = new BABYLON.Matrix();
  26884. this._t0 = BABYLON.Vector3.Zero();
  26885. this._t1 = BABYLON.Vector3.Zero();
  26886. this._t2 = BABYLON.Vector3.Zero();
  26887. }
  26888. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26889. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26890. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26891. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26892. this._t1.subtractInPlace(this._t0);
  26893. this._t2.subtractInPlace(this._t0);
  26894. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26895. this._cachedTextureMatrix.m[0] = this._t1.x;
  26896. this._cachedTextureMatrix.m[1] = this._t1.y;
  26897. this._cachedTextureMatrix.m[2] = this._t1.z;
  26898. this._cachedTextureMatrix.m[4] = this._t2.x;
  26899. this._cachedTextureMatrix.m[5] = this._t2.y;
  26900. this._cachedTextureMatrix.m[6] = this._t2.z;
  26901. this._cachedTextureMatrix.m[8] = this._t0.x;
  26902. this._cachedTextureMatrix.m[9] = this._t0.y;
  26903. this._cachedTextureMatrix.m[10] = this._t0.z;
  26904. var scene = this.getScene();
  26905. if (!scene) {
  26906. return this._cachedTextureMatrix;
  26907. }
  26908. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26909. return mat.hasTexture(_this);
  26910. });
  26911. return this._cachedTextureMatrix;
  26912. };
  26913. Texture.prototype.getReflectionTextureMatrix = function () {
  26914. var _this = this;
  26915. var scene = this.getScene();
  26916. if (!scene) {
  26917. return this._cachedTextureMatrix;
  26918. }
  26919. if (this.uOffset === this._cachedUOffset &&
  26920. this.vOffset === this._cachedVOffset &&
  26921. this.uScale === this._cachedUScale &&
  26922. this.vScale === this._cachedVScale &&
  26923. this.coordinatesMode === this._cachedCoordinatesMode) {
  26924. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26925. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26926. return this._cachedTextureMatrix;
  26927. }
  26928. }
  26929. else {
  26930. return this._cachedTextureMatrix;
  26931. }
  26932. }
  26933. if (!this._cachedTextureMatrix) {
  26934. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26935. }
  26936. if (!this._projectionModeMatrix) {
  26937. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26938. }
  26939. this._cachedUOffset = this.uOffset;
  26940. this._cachedVOffset = this.vOffset;
  26941. this._cachedUScale = this.uScale;
  26942. this._cachedVScale = this.vScale;
  26943. this._cachedCoordinatesMode = this.coordinatesMode;
  26944. switch (this.coordinatesMode) {
  26945. case Texture.PLANAR_MODE:
  26946. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26947. this._cachedTextureMatrix[0] = this.uScale;
  26948. this._cachedTextureMatrix[5] = this.vScale;
  26949. this._cachedTextureMatrix[12] = this.uOffset;
  26950. this._cachedTextureMatrix[13] = this.vOffset;
  26951. break;
  26952. case Texture.PROJECTION_MODE:
  26953. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26954. this._projectionModeMatrix.m[0] = 0.5;
  26955. this._projectionModeMatrix.m[5] = -0.5;
  26956. this._projectionModeMatrix.m[10] = 0.0;
  26957. this._projectionModeMatrix.m[12] = 0.5;
  26958. this._projectionModeMatrix.m[13] = 0.5;
  26959. this._projectionModeMatrix.m[14] = 1.0;
  26960. this._projectionModeMatrix.m[15] = 1.0;
  26961. var projectionMatrix = scene.getProjectionMatrix();
  26962. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26963. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26964. break;
  26965. default:
  26966. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26967. break;
  26968. }
  26969. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26970. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26971. });
  26972. return this._cachedTextureMatrix;
  26973. };
  26974. Texture.prototype.clone = function () {
  26975. var _this = this;
  26976. return BABYLON.SerializationHelper.Clone(function () {
  26977. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26978. }, this);
  26979. };
  26980. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26981. get: function () {
  26982. if (!this._onLoadObservable) {
  26983. this._onLoadObservable = new BABYLON.Observable();
  26984. }
  26985. return this._onLoadObservable;
  26986. },
  26987. enumerable: true,
  26988. configurable: true
  26989. });
  26990. Texture.prototype.serialize = function () {
  26991. var serializationObject = _super.prototype.serialize.call(this);
  26992. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26993. serializationObject.base64String = this._buffer;
  26994. serializationObject.name = serializationObject.name.replace("data:", "");
  26995. }
  26996. return serializationObject;
  26997. };
  26998. Texture.prototype.getClassName = function () {
  26999. return "Texture";
  27000. };
  27001. Texture.prototype.dispose = function () {
  27002. _super.prototype.dispose.call(this);
  27003. if (this.onLoadObservable) {
  27004. this.onLoadObservable.clear();
  27005. this._onLoadObservable = null;
  27006. }
  27007. this._delayedOnLoad = null;
  27008. this._delayedOnError = null;
  27009. };
  27010. // Statics
  27011. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27012. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27013. if (onLoad === void 0) { onLoad = null; }
  27014. if (onError === void 0) { onError = null; }
  27015. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27016. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27017. };
  27018. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27019. if (parsedTexture.customType) {
  27020. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27021. // Update Sampling Mode
  27022. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27023. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27024. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27025. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27026. }
  27027. }
  27028. return parsedCustomTexture;
  27029. }
  27030. if (parsedTexture.isCube) {
  27031. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27032. }
  27033. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27034. return null;
  27035. }
  27036. var texture = BABYLON.SerializationHelper.Parse(function () {
  27037. var generateMipMaps = true;
  27038. if (parsedTexture.noMipmap) {
  27039. generateMipMaps = false;
  27040. }
  27041. if (parsedTexture.mirrorPlane) {
  27042. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27043. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27044. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27045. return mirrorTexture;
  27046. }
  27047. else if (parsedTexture.isRenderTarget) {
  27048. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27049. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27050. return renderTargetTexture;
  27051. }
  27052. else {
  27053. var texture;
  27054. if (parsedTexture.base64String) {
  27055. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27056. }
  27057. else {
  27058. var url = rootUrl + parsedTexture.name;
  27059. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27060. url = parsedTexture.url;
  27061. }
  27062. texture = new Texture(url, scene, !generateMipMaps);
  27063. }
  27064. return texture;
  27065. }
  27066. }, parsedTexture, scene);
  27067. // Update Sampling Mode
  27068. if (parsedTexture.samplingMode) {
  27069. var sampling = parsedTexture.samplingMode;
  27070. if (texture._samplingMode !== sampling) {
  27071. texture.updateSamplingMode(sampling);
  27072. }
  27073. }
  27074. // Animations
  27075. if (parsedTexture.animations) {
  27076. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27077. var parsedAnimation = parsedTexture.animations[animationIndex];
  27078. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27079. }
  27080. }
  27081. return texture;
  27082. };
  27083. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27084. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27085. if (noMipmap === void 0) { noMipmap = false; }
  27086. if (invertY === void 0) { invertY = true; }
  27087. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27088. if (onLoad === void 0) { onLoad = null; }
  27089. if (onError === void 0) { onError = null; }
  27090. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27091. if (name.substr(0, 5) !== "data:") {
  27092. name = "data:" + name;
  27093. }
  27094. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27095. };
  27096. // Constants
  27097. Texture.NEAREST_SAMPLINGMODE = 1;
  27098. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27099. Texture.BILINEAR_SAMPLINGMODE = 2;
  27100. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27101. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27102. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27103. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27104. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27105. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27106. Texture.NEAREST_LINEAR = 7;
  27107. Texture.NEAREST_NEAREST = 8;
  27108. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27109. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27110. Texture.LINEAR_LINEAR = 11;
  27111. Texture.LINEAR_NEAREST = 12;
  27112. Texture.EXPLICIT_MODE = 0;
  27113. Texture.SPHERICAL_MODE = 1;
  27114. Texture.PLANAR_MODE = 2;
  27115. Texture.CUBIC_MODE = 3;
  27116. Texture.PROJECTION_MODE = 4;
  27117. Texture.SKYBOX_MODE = 5;
  27118. Texture.INVCUBIC_MODE = 6;
  27119. Texture.EQUIRECTANGULAR_MODE = 7;
  27120. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27121. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27122. Texture.CLAMP_ADDRESSMODE = 0;
  27123. Texture.WRAP_ADDRESSMODE = 1;
  27124. Texture.MIRROR_ADDRESSMODE = 2;
  27125. /**
  27126. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27127. */
  27128. Texture.UseSerializedUrlIfAny = false;
  27129. __decorate([
  27130. BABYLON.serialize()
  27131. ], Texture.prototype, "url", void 0);
  27132. __decorate([
  27133. BABYLON.serialize()
  27134. ], Texture.prototype, "uOffset", void 0);
  27135. __decorate([
  27136. BABYLON.serialize()
  27137. ], Texture.prototype, "vOffset", void 0);
  27138. __decorate([
  27139. BABYLON.serialize()
  27140. ], Texture.prototype, "uScale", void 0);
  27141. __decorate([
  27142. BABYLON.serialize()
  27143. ], Texture.prototype, "vScale", void 0);
  27144. __decorate([
  27145. BABYLON.serialize()
  27146. ], Texture.prototype, "uAng", void 0);
  27147. __decorate([
  27148. BABYLON.serialize()
  27149. ], Texture.prototype, "vAng", void 0);
  27150. __decorate([
  27151. BABYLON.serialize()
  27152. ], Texture.prototype, "wAng", void 0);
  27153. __decorate([
  27154. BABYLON.serialize()
  27155. ], Texture.prototype, "isBlocking", null);
  27156. return Texture;
  27157. }(BABYLON.BaseTexture));
  27158. BABYLON.Texture = Texture;
  27159. })(BABYLON || (BABYLON = {}));
  27160. //# sourceMappingURL=babylon.texture.js.map
  27161. var BABYLON;
  27162. (function (BABYLON) {
  27163. var _InstancesBatch = /** @class */ (function () {
  27164. function _InstancesBatch() {
  27165. this.mustReturn = false;
  27166. this.visibleInstances = new Array();
  27167. this.renderSelf = new Array();
  27168. }
  27169. return _InstancesBatch;
  27170. }());
  27171. BABYLON._InstancesBatch = _InstancesBatch;
  27172. var Mesh = /** @class */ (function (_super) {
  27173. __extends(Mesh, _super);
  27174. /**
  27175. * @constructor
  27176. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27177. * @param {Scene} scene The scene to add this mesh to.
  27178. * @param {Node} parent The parent of this mesh, if it has one
  27179. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27180. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27181. * When false, achieved by calling a clone(), also passing False.
  27182. * This will make creation of children, recursive.
  27183. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27184. */
  27185. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27186. if (scene === void 0) { scene = null; }
  27187. if (parent === void 0) { parent = null; }
  27188. if (source === void 0) { source = null; }
  27189. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27190. var _this = _super.call(this, name, scene) || this;
  27191. // Events
  27192. /**
  27193. * An event triggered before rendering the mesh
  27194. * @type {BABYLON.Observable}
  27195. */
  27196. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27197. /**
  27198. * An event triggered after rendering the mesh
  27199. * @type {BABYLON.Observable}
  27200. */
  27201. _this.onAfterRenderObservable = new BABYLON.Observable();
  27202. /**
  27203. * An event triggered before drawing the mesh
  27204. * @type {BABYLON.Observable}
  27205. */
  27206. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27207. // Members
  27208. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27209. _this.instances = new Array();
  27210. _this._LODLevels = new Array();
  27211. _this._visibleInstances = {};
  27212. _this._renderIdForInstances = new Array();
  27213. _this._batchCache = new _InstancesBatch();
  27214. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27215. // Use by builder only to know what orientation were the mesh build in.
  27216. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27217. _this.overrideMaterialSideOrientation = null;
  27218. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27219. // Will be used to save a source mesh reference, If any
  27220. _this._source = null;
  27221. scene = _this.getScene();
  27222. if (source) {
  27223. // Source mesh
  27224. _this._source = source;
  27225. // Geometry
  27226. if (source._geometry) {
  27227. source._geometry.applyToMesh(_this);
  27228. }
  27229. // Deep copy
  27230. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27231. // Metadata
  27232. if (source.metadata && source.metadata.clone) {
  27233. _this.metadata = source.metadata.clone();
  27234. }
  27235. else {
  27236. _this.metadata = source.metadata;
  27237. }
  27238. // Tags
  27239. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27240. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27241. }
  27242. // Parent
  27243. _this.parent = source.parent;
  27244. // Pivot
  27245. _this.setPivotMatrix(source.getPivotMatrix());
  27246. _this.id = name + "." + source.id;
  27247. // Material
  27248. _this.material = source.material;
  27249. var index;
  27250. if (!doNotCloneChildren) {
  27251. // Children
  27252. var directDescendants = source.getDescendants(true);
  27253. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27254. var child = directDescendants[index_1];
  27255. if (child.clone) {
  27256. child.clone(name + "." + child.name, _this);
  27257. }
  27258. }
  27259. }
  27260. // Physics clone
  27261. var physicsEngine = _this.getScene().getPhysicsEngine();
  27262. if (clonePhysicsImpostor && physicsEngine) {
  27263. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27264. if (impostor) {
  27265. _this.physicsImpostor = impostor.clone(_this);
  27266. }
  27267. }
  27268. // Particles
  27269. for (index = 0; index < scene.particleSystems.length; index++) {
  27270. var system = scene.particleSystems[index];
  27271. if (system.emitter === source) {
  27272. system.clone(system.name, _this);
  27273. }
  27274. }
  27275. _this.computeWorldMatrix(true);
  27276. }
  27277. // Parent
  27278. if (parent !== null) {
  27279. _this.parent = parent;
  27280. }
  27281. return _this;
  27282. }
  27283. Object.defineProperty(Mesh, "FRONTSIDE", {
  27284. /**
  27285. * Mesh side orientation : usually the external or front surface
  27286. */
  27287. get: function () {
  27288. return Mesh._FRONTSIDE;
  27289. },
  27290. enumerable: true,
  27291. configurable: true
  27292. });
  27293. Object.defineProperty(Mesh, "BACKSIDE", {
  27294. /**
  27295. * Mesh side orientation : usually the internal or back surface
  27296. */
  27297. get: function () {
  27298. return Mesh._BACKSIDE;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27304. /**
  27305. * Mesh side orientation : both internal and external or front and back surfaces
  27306. */
  27307. get: function () {
  27308. return Mesh._DOUBLESIDE;
  27309. },
  27310. enumerable: true,
  27311. configurable: true
  27312. });
  27313. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27314. /**
  27315. * Mesh side orientation : by default, `FRONTSIDE`
  27316. */
  27317. get: function () {
  27318. return Mesh._DEFAULTSIDE;
  27319. },
  27320. enumerable: true,
  27321. configurable: true
  27322. });
  27323. Object.defineProperty(Mesh, "NO_CAP", {
  27324. /**
  27325. * Mesh cap setting : no cap
  27326. */
  27327. get: function () {
  27328. return Mesh._NO_CAP;
  27329. },
  27330. enumerable: true,
  27331. configurable: true
  27332. });
  27333. Object.defineProperty(Mesh, "CAP_START", {
  27334. /**
  27335. * Mesh cap setting : one cap at the beginning of the mesh
  27336. */
  27337. get: function () {
  27338. return Mesh._CAP_START;
  27339. },
  27340. enumerable: true,
  27341. configurable: true
  27342. });
  27343. Object.defineProperty(Mesh, "CAP_END", {
  27344. /**
  27345. * Mesh cap setting : one cap at the end of the mesh
  27346. */
  27347. get: function () {
  27348. return Mesh._CAP_END;
  27349. },
  27350. enumerable: true,
  27351. configurable: true
  27352. });
  27353. Object.defineProperty(Mesh, "CAP_ALL", {
  27354. /**
  27355. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27356. */
  27357. get: function () {
  27358. return Mesh._CAP_ALL;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27364. set: function (callback) {
  27365. if (this._onBeforeDrawObserver) {
  27366. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27367. }
  27368. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27369. },
  27370. enumerable: true,
  27371. configurable: true
  27372. });
  27373. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27374. get: function () {
  27375. return this._morphTargetManager;
  27376. },
  27377. set: function (value) {
  27378. if (this._morphTargetManager === value) {
  27379. return;
  27380. }
  27381. this._morphTargetManager = value;
  27382. this._syncGeometryWithMorphTargetManager();
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Object.defineProperty(Mesh.prototype, "source", {
  27388. get: function () {
  27389. return this._source;
  27390. },
  27391. enumerable: true,
  27392. configurable: true
  27393. });
  27394. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27395. get: function () {
  27396. return this._unIndexed;
  27397. },
  27398. set: function (value) {
  27399. if (this._unIndexed !== value) {
  27400. this._unIndexed = value;
  27401. this._markSubMeshesAsAttributesDirty();
  27402. }
  27403. },
  27404. enumerable: true,
  27405. configurable: true
  27406. });
  27407. // Methods
  27408. /**
  27409. * Returns the string "Mesh".
  27410. */
  27411. Mesh.prototype.getClassName = function () {
  27412. return "Mesh";
  27413. };
  27414. /**
  27415. * Returns a string.
  27416. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27417. */
  27418. Mesh.prototype.toString = function (fullDetails) {
  27419. var ret = _super.prototype.toString.call(this, fullDetails);
  27420. ret += ", n vertices: " + this.getTotalVertices();
  27421. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27422. if (this.animations) {
  27423. for (var i = 0; i < this.animations.length; i++) {
  27424. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27425. }
  27426. }
  27427. if (fullDetails) {
  27428. if (this._geometry) {
  27429. var ib = this.getIndices();
  27430. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27431. if (vb && ib) {
  27432. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27433. }
  27434. }
  27435. else {
  27436. ret += ", flat shading: UNKNOWN";
  27437. }
  27438. }
  27439. return ret;
  27440. };
  27441. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27442. /**
  27443. * True if the mesh has some Levels Of Details (LOD).
  27444. * Returns a boolean.
  27445. */
  27446. get: function () {
  27447. return this._LODLevels.length > 0;
  27448. },
  27449. enumerable: true,
  27450. configurable: true
  27451. });
  27452. /**
  27453. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27454. * @returns an array of {BABYLON.MeshLODLevel}
  27455. */
  27456. Mesh.prototype.getLODLevels = function () {
  27457. return this._LODLevels;
  27458. };
  27459. Mesh.prototype._sortLODLevels = function () {
  27460. this._LODLevels.sort(function (a, b) {
  27461. if (a.distance < b.distance) {
  27462. return 1;
  27463. }
  27464. if (a.distance > b.distance) {
  27465. return -1;
  27466. }
  27467. return 0;
  27468. });
  27469. };
  27470. /**
  27471. * Add a mesh as LOD level triggered at the given distance.
  27472. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27473. * @param {number} distance The distance from the center of the object to show this level
  27474. * @param {Mesh} mesh The mesh to be added as LOD level
  27475. * @return {Mesh} This mesh (for chaining)
  27476. */
  27477. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27478. if (mesh && mesh._masterMesh) {
  27479. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27480. return this;
  27481. }
  27482. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27483. this._LODLevels.push(level);
  27484. if (mesh) {
  27485. mesh._masterMesh = this;
  27486. }
  27487. this._sortLODLevels();
  27488. return this;
  27489. };
  27490. /**
  27491. * Returns the LOD level mesh at the passed distance or null if not found.
  27492. * It is related to the method `addLODLevel(distance, mesh)`.
  27493. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27494. * Returns an object Mesh or `null`.
  27495. */
  27496. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27497. for (var index = 0; index < this._LODLevels.length; index++) {
  27498. var level = this._LODLevels[index];
  27499. if (level.distance === distance) {
  27500. return level.mesh;
  27501. }
  27502. }
  27503. return null;
  27504. };
  27505. /**
  27506. * Remove a mesh from the LOD array
  27507. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27508. * @param {Mesh} mesh The mesh to be removed.
  27509. * @return {Mesh} This mesh (for chaining)
  27510. */
  27511. Mesh.prototype.removeLODLevel = function (mesh) {
  27512. for (var index = 0; index < this._LODLevels.length; index++) {
  27513. if (this._LODLevels[index].mesh === mesh) {
  27514. this._LODLevels.splice(index, 1);
  27515. if (mesh) {
  27516. mesh._masterMesh = null;
  27517. }
  27518. }
  27519. }
  27520. this._sortLODLevels();
  27521. return this;
  27522. };
  27523. /**
  27524. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27525. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27526. */
  27527. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27528. if (!this._LODLevels || this._LODLevels.length === 0) {
  27529. return this;
  27530. }
  27531. var bSphere;
  27532. if (boundingSphere) {
  27533. bSphere = boundingSphere;
  27534. }
  27535. else {
  27536. var boundingInfo = this.getBoundingInfo();
  27537. bSphere = boundingInfo.boundingSphere;
  27538. }
  27539. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27540. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27541. if (this.onLODLevelSelection) {
  27542. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27543. }
  27544. return this;
  27545. }
  27546. for (var index = 0; index < this._LODLevels.length; index++) {
  27547. var level = this._LODLevels[index];
  27548. if (level.distance < distanceToCamera) {
  27549. if (level.mesh) {
  27550. level.mesh._preActivate();
  27551. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27552. }
  27553. if (this.onLODLevelSelection) {
  27554. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27555. }
  27556. return level.mesh;
  27557. }
  27558. }
  27559. if (this.onLODLevelSelection) {
  27560. this.onLODLevelSelection(distanceToCamera, this, this);
  27561. }
  27562. return this;
  27563. };
  27564. Object.defineProperty(Mesh.prototype, "geometry", {
  27565. /**
  27566. * Returns the mesh internal Geometry object.
  27567. */
  27568. get: function () {
  27569. return this._geometry;
  27570. },
  27571. enumerable: true,
  27572. configurable: true
  27573. });
  27574. /**
  27575. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27576. */
  27577. Mesh.prototype.getTotalVertices = function () {
  27578. if (this._geometry === null || this._geometry === undefined) {
  27579. return 0;
  27580. }
  27581. return this._geometry.getTotalVertices();
  27582. };
  27583. /**
  27584. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27585. * 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.
  27586. * You can force the copy with forceCopy === true
  27587. * Returns null if the mesh has no geometry or no vertex buffer.
  27588. * Possible `kind` values :
  27589. * - BABYLON.VertexBuffer.PositionKind
  27590. * - BABYLON.VertexBuffer.UVKind
  27591. * - BABYLON.VertexBuffer.UV2Kind
  27592. * - BABYLON.VertexBuffer.UV3Kind
  27593. * - BABYLON.VertexBuffer.UV4Kind
  27594. * - BABYLON.VertexBuffer.UV5Kind
  27595. * - BABYLON.VertexBuffer.UV6Kind
  27596. * - BABYLON.VertexBuffer.ColorKind
  27597. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27598. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27599. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27600. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27601. */
  27602. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27603. if (!this._geometry) {
  27604. return null;
  27605. }
  27606. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27607. };
  27608. /**
  27609. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27610. * Returns `null` if the mesh has no geometry.
  27611. * Possible `kind` values :
  27612. * - BABYLON.VertexBuffer.PositionKind
  27613. * - BABYLON.VertexBuffer.UVKind
  27614. * - BABYLON.VertexBuffer.UV2Kind
  27615. * - BABYLON.VertexBuffer.UV3Kind
  27616. * - BABYLON.VertexBuffer.UV4Kind
  27617. * - BABYLON.VertexBuffer.UV5Kind
  27618. * - BABYLON.VertexBuffer.UV6Kind
  27619. * - BABYLON.VertexBuffer.ColorKind
  27620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27624. */
  27625. Mesh.prototype.getVertexBuffer = function (kind) {
  27626. if (!this._geometry) {
  27627. return null;
  27628. }
  27629. return this._geometry.getVertexBuffer(kind);
  27630. };
  27631. /**
  27632. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27633. * Possible `kind` values :
  27634. * - BABYLON.VertexBuffer.PositionKind
  27635. * - BABYLON.VertexBuffer.UVKind
  27636. * - BABYLON.VertexBuffer.UV2Kind
  27637. * - BABYLON.VertexBuffer.UV3Kind
  27638. * - BABYLON.VertexBuffer.UV4Kind
  27639. * - BABYLON.VertexBuffer.UV5Kind
  27640. * - BABYLON.VertexBuffer.UV6Kind
  27641. * - BABYLON.VertexBuffer.ColorKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27646. */
  27647. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27648. if (!this._geometry) {
  27649. if (this._delayInfo) {
  27650. return this._delayInfo.indexOf(kind) !== -1;
  27651. }
  27652. return false;
  27653. }
  27654. return this._geometry.isVerticesDataPresent(kind);
  27655. };
  27656. /**
  27657. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27658. * Possible `kind` values :
  27659. * - BABYLON.VertexBuffer.PositionKind
  27660. * - BABYLON.VertexBuffer.UVKind
  27661. * - BABYLON.VertexBuffer.UV2Kind
  27662. * - BABYLON.VertexBuffer.UV3Kind
  27663. * - BABYLON.VertexBuffer.UV4Kind
  27664. * - BABYLON.VertexBuffer.UV5Kind
  27665. * - BABYLON.VertexBuffer.UV6Kind
  27666. * - BABYLON.VertexBuffer.ColorKind
  27667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27671. */
  27672. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27673. if (!this._geometry) {
  27674. if (this._delayInfo) {
  27675. return this._delayInfo.indexOf(kind) !== -1;
  27676. }
  27677. return false;
  27678. }
  27679. return this._geometry.isVertexBufferUpdatable(kind);
  27680. };
  27681. /**
  27682. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27683. * Possible `kind` values :
  27684. * - BABYLON.VertexBuffer.PositionKind
  27685. * - BABYLON.VertexBuffer.UVKind
  27686. * - BABYLON.VertexBuffer.UV2Kind
  27687. * - BABYLON.VertexBuffer.UV3Kind
  27688. * - BABYLON.VertexBuffer.UV4Kind
  27689. * - BABYLON.VertexBuffer.UV5Kind
  27690. * - BABYLON.VertexBuffer.UV6Kind
  27691. * - BABYLON.VertexBuffer.ColorKind
  27692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27696. */
  27697. Mesh.prototype.getVerticesDataKinds = function () {
  27698. if (!this._geometry) {
  27699. var result = new Array();
  27700. if (this._delayInfo) {
  27701. this._delayInfo.forEach(function (kind, index, array) {
  27702. result.push(kind);
  27703. });
  27704. }
  27705. return result;
  27706. }
  27707. return this._geometry.getVerticesDataKinds();
  27708. };
  27709. /**
  27710. * Returns a positive integer : the total number of indices in this mesh geometry.
  27711. * Returns zero if the mesh has no geometry.
  27712. */
  27713. Mesh.prototype.getTotalIndices = function () {
  27714. if (!this._geometry) {
  27715. return 0;
  27716. }
  27717. return this._geometry.getTotalIndices();
  27718. };
  27719. /**
  27720. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27721. * 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.
  27722. * Returns an empty array if the mesh has no geometry.
  27723. */
  27724. Mesh.prototype.getIndices = function (copyWhenShared) {
  27725. if (!this._geometry) {
  27726. return [];
  27727. }
  27728. return this._geometry.getIndices(copyWhenShared);
  27729. };
  27730. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27731. get: function () {
  27732. return this._masterMesh !== null && this._masterMesh !== undefined;
  27733. },
  27734. enumerable: true,
  27735. configurable: true
  27736. });
  27737. /**
  27738. * Determine if the current mesh is ready to be rendered
  27739. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27740. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27741. * @returns true if all associated assets are ready (material, textures, shaders)
  27742. */
  27743. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27744. if (completeCheck === void 0) { completeCheck = false; }
  27745. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27746. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27747. return false;
  27748. }
  27749. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27750. return false;
  27751. }
  27752. if (!this.subMeshes || this.subMeshes.length === 0) {
  27753. return true;
  27754. }
  27755. if (!completeCheck) {
  27756. return true;
  27757. }
  27758. var engine = this.getEngine();
  27759. var scene = this.getScene();
  27760. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27761. this.computeWorldMatrix();
  27762. var mat = this.material || scene.defaultMaterial;
  27763. if (mat) {
  27764. if (mat.storeEffectOnSubMeshes) {
  27765. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27766. var subMesh = _a[_i];
  27767. var effectiveMaterial = subMesh.getMaterial();
  27768. if (effectiveMaterial) {
  27769. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27770. return false;
  27771. }
  27772. }
  27773. }
  27774. }
  27775. else {
  27776. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27777. return false;
  27778. }
  27779. }
  27780. }
  27781. // Shadows
  27782. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27783. var light = _c[_b];
  27784. var generator = light.getShadowGenerator();
  27785. if (generator) {
  27786. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27787. var subMesh = _e[_d];
  27788. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27789. return false;
  27790. }
  27791. }
  27792. }
  27793. }
  27794. // LOD
  27795. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27796. var lod = _g[_f];
  27797. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27798. return false;
  27799. }
  27800. }
  27801. return true;
  27802. };
  27803. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27804. /**
  27805. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27806. * This property is pertinent only for updatable parametric shapes.
  27807. */
  27808. get: function () {
  27809. return this._areNormalsFrozen;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. /**
  27815. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27816. * It has no effect at all on other shapes.
  27817. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27818. * Returns the Mesh.
  27819. */
  27820. Mesh.prototype.freezeNormals = function () {
  27821. this._areNormalsFrozen = true;
  27822. return this;
  27823. };
  27824. /**
  27825. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27826. * It has no effect at all on other shapes.
  27827. * It reactivates the mesh normals computation if it was previously frozen.
  27828. * Returns the Mesh.
  27829. */
  27830. Mesh.prototype.unfreezeNormals = function () {
  27831. this._areNormalsFrozen = false;
  27832. return this;
  27833. };
  27834. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27835. /**
  27836. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27837. */
  27838. set: function (count) {
  27839. this._overridenInstanceCount = count;
  27840. },
  27841. enumerable: true,
  27842. configurable: true
  27843. });
  27844. // Methods
  27845. Mesh.prototype._preActivate = function () {
  27846. var sceneRenderId = this.getScene().getRenderId();
  27847. if (this._preActivateId === sceneRenderId) {
  27848. return this;
  27849. }
  27850. this._preActivateId = sceneRenderId;
  27851. this._visibleInstances = null;
  27852. return this;
  27853. };
  27854. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27855. if (this._visibleInstances) {
  27856. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27857. }
  27858. return this;
  27859. };
  27860. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27861. if (!this._visibleInstances) {
  27862. this._visibleInstances = {};
  27863. this._visibleInstances.defaultRenderId = renderId;
  27864. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27865. }
  27866. if (!this._visibleInstances[renderId]) {
  27867. this._visibleInstances[renderId] = new Array();
  27868. }
  27869. this._visibleInstances[renderId].push(instance);
  27870. return this;
  27871. };
  27872. /**
  27873. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27874. * This means the mesh underlying bounding box and sphere are recomputed.
  27875. * Returns the Mesh.
  27876. */
  27877. Mesh.prototype.refreshBoundingInfo = function () {
  27878. return this._refreshBoundingInfo(false);
  27879. };
  27880. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27881. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27882. return this;
  27883. }
  27884. var data = this._getPositionData(applySkeleton);
  27885. if (data) {
  27886. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27887. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27888. }
  27889. if (this.subMeshes) {
  27890. for (var index = 0; index < this.subMeshes.length; index++) {
  27891. this.subMeshes[index].refreshBoundingInfo();
  27892. }
  27893. }
  27894. this._updateBoundingInfo();
  27895. return this;
  27896. };
  27897. Mesh.prototype._getPositionData = function (applySkeleton) {
  27898. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27899. if (data && applySkeleton && this.skeleton) {
  27900. data = BABYLON.Tools.Slice(data);
  27901. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27902. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27903. if (matricesWeightsData && matricesIndicesData) {
  27904. var needExtras = this.numBoneInfluencers > 4;
  27905. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27906. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27907. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27908. var tempVector = BABYLON.Tmp.Vector3[0];
  27909. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27910. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27911. var matWeightIdx = 0;
  27912. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27913. finalMatrix.reset();
  27914. var inf;
  27915. var weight;
  27916. for (inf = 0; inf < 4; inf++) {
  27917. weight = matricesWeightsData[matWeightIdx + inf];
  27918. if (weight <= 0)
  27919. break;
  27920. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27921. finalMatrix.addToSelf(tempMatrix);
  27922. }
  27923. if (needExtras) {
  27924. for (inf = 0; inf < 4; inf++) {
  27925. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27926. if (weight <= 0)
  27927. break;
  27928. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27929. finalMatrix.addToSelf(tempMatrix);
  27930. }
  27931. }
  27932. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27933. tempVector.toArray(data, index);
  27934. }
  27935. }
  27936. }
  27937. return data;
  27938. };
  27939. Mesh.prototype._createGlobalSubMesh = function (force) {
  27940. var totalVertices = this.getTotalVertices();
  27941. if (!totalVertices || !this.getIndices()) {
  27942. return null;
  27943. }
  27944. // Check if we need to recreate the submeshes
  27945. if (this.subMeshes && this.subMeshes.length > 0) {
  27946. var ib = this.getIndices();
  27947. if (!ib) {
  27948. return null;
  27949. }
  27950. var totalIndices = ib.length;
  27951. var needToRecreate = false;
  27952. if (force) {
  27953. needToRecreate = true;
  27954. }
  27955. else {
  27956. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27957. var submesh = _a[_i];
  27958. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27959. needToRecreate = true;
  27960. break;
  27961. }
  27962. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27963. needToRecreate = true;
  27964. break;
  27965. }
  27966. }
  27967. }
  27968. if (!needToRecreate) {
  27969. return this.subMeshes[0];
  27970. }
  27971. }
  27972. this.releaseSubMeshes();
  27973. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27974. };
  27975. Mesh.prototype.subdivide = function (count) {
  27976. if (count < 1) {
  27977. return;
  27978. }
  27979. var totalIndices = this.getTotalIndices();
  27980. var subdivisionSize = (totalIndices / count) | 0;
  27981. var offset = 0;
  27982. // Ensure that subdivisionSize is a multiple of 3
  27983. while (subdivisionSize % 3 !== 0) {
  27984. subdivisionSize++;
  27985. }
  27986. this.releaseSubMeshes();
  27987. for (var index = 0; index < count; index++) {
  27988. if (offset >= totalIndices) {
  27989. break;
  27990. }
  27991. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27992. offset += subdivisionSize;
  27993. }
  27994. this.synchronizeInstances();
  27995. };
  27996. /**
  27997. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27998. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27999. * The `data` are either a numeric array either a Float32Array.
  28000. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28001. * 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).
  28002. * Note that a new underlying VertexBuffer object is created each call.
  28003. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28004. *
  28005. * Possible `kind` values :
  28006. * - BABYLON.VertexBuffer.PositionKind
  28007. * - BABYLON.VertexBuffer.UVKind
  28008. * - BABYLON.VertexBuffer.UV2Kind
  28009. * - BABYLON.VertexBuffer.UV3Kind
  28010. * - BABYLON.VertexBuffer.UV4Kind
  28011. * - BABYLON.VertexBuffer.UV5Kind
  28012. * - BABYLON.VertexBuffer.UV6Kind
  28013. * - BABYLON.VertexBuffer.ColorKind
  28014. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28015. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28016. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28017. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28018. *
  28019. * Returns the Mesh.
  28020. */
  28021. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28022. if (updatable === void 0) { updatable = false; }
  28023. if (!this._geometry) {
  28024. var vertexData = new BABYLON.VertexData();
  28025. vertexData.set(data, kind);
  28026. var scene = this.getScene();
  28027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28028. }
  28029. else {
  28030. this._geometry.setVerticesData(kind, data, updatable, stride);
  28031. }
  28032. return this;
  28033. };
  28034. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28035. if (updatable === void 0) { updatable = true; }
  28036. var vb = this.getVertexBuffer(kind);
  28037. if (!vb || vb.isUpdatable() === updatable) {
  28038. return;
  28039. }
  28040. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28041. };
  28042. /**
  28043. * Sets the mesh VertexBuffer.
  28044. * Returns the Mesh.
  28045. */
  28046. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28047. if (!this._geometry) {
  28048. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28049. }
  28050. this._geometry.setVerticesBuffer(buffer);
  28051. return this;
  28052. };
  28053. /**
  28054. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28055. * If the mesh has no geometry, it is simply returned as it is.
  28056. * The `data` are either a numeric array either a Float32Array.
  28057. * No new underlying VertexBuffer object is created.
  28058. * 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.
  28059. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28060. *
  28061. * Possible `kind` values :
  28062. * - BABYLON.VertexBuffer.PositionKind
  28063. * - BABYLON.VertexBuffer.UVKind
  28064. * - BABYLON.VertexBuffer.UV2Kind
  28065. * - BABYLON.VertexBuffer.UV3Kind
  28066. * - BABYLON.VertexBuffer.UV4Kind
  28067. * - BABYLON.VertexBuffer.UV5Kind
  28068. * - BABYLON.VertexBuffer.UV6Kind
  28069. * - BABYLON.VertexBuffer.ColorKind
  28070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28074. *
  28075. * Returns the Mesh.
  28076. */
  28077. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28078. if (!this._geometry) {
  28079. return this;
  28080. }
  28081. if (!makeItUnique) {
  28082. this._geometry.updateVerticesData(kind, data, updateExtends);
  28083. }
  28084. else {
  28085. this.makeGeometryUnique();
  28086. this.updateVerticesData(kind, data, updateExtends, false);
  28087. }
  28088. return this;
  28089. };
  28090. /**
  28091. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28092. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28093. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28094. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28095. * Returns the Mesh.
  28096. */
  28097. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28098. if (computeNormals === void 0) { computeNormals = true; }
  28099. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28100. if (!positions) {
  28101. return this;
  28102. }
  28103. positionFunction(positions);
  28104. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28105. if (computeNormals) {
  28106. var indices = this.getIndices();
  28107. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28108. if (!normals) {
  28109. return this;
  28110. }
  28111. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28112. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28113. }
  28114. return this;
  28115. };
  28116. /**
  28117. * Creates a un-shared specific occurence of the geometry for the mesh.
  28118. * Returns the Mesh.
  28119. */
  28120. Mesh.prototype.makeGeometryUnique = function () {
  28121. if (!this._geometry) {
  28122. return this;
  28123. }
  28124. var oldGeometry = this._geometry;
  28125. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28126. oldGeometry.releaseForMesh(this, true);
  28127. geometry.applyToMesh(this);
  28128. return this;
  28129. };
  28130. /**
  28131. * Sets the mesh indices.
  28132. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28133. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28134. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28135. * This method creates a new index buffer each call.
  28136. * Returns the Mesh.
  28137. */
  28138. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28139. if (totalVertices === void 0) { totalVertices = null; }
  28140. if (updatable === void 0) { updatable = false; }
  28141. if (!this._geometry) {
  28142. var vertexData = new BABYLON.VertexData();
  28143. vertexData.indices = indices;
  28144. var scene = this.getScene();
  28145. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28146. }
  28147. else {
  28148. this._geometry.setIndices(indices, totalVertices, updatable);
  28149. }
  28150. return this;
  28151. };
  28152. /**
  28153. * Update the current index buffer
  28154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28155. * Returns the Mesh.
  28156. */
  28157. Mesh.prototype.updateIndices = function (indices, offset) {
  28158. if (!this._geometry) {
  28159. return this;
  28160. }
  28161. this._geometry.updateIndices(indices, offset);
  28162. return this;
  28163. };
  28164. /**
  28165. * Invert the geometry to move from a right handed system to a left handed one.
  28166. * Returns the Mesh.
  28167. */
  28168. Mesh.prototype.toLeftHanded = function () {
  28169. if (!this._geometry) {
  28170. return this;
  28171. }
  28172. this._geometry.toLeftHanded();
  28173. return this;
  28174. };
  28175. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28176. if (!this._geometry) {
  28177. return this;
  28178. }
  28179. var engine = this.getScene().getEngine();
  28180. // Wireframe
  28181. var indexToBind;
  28182. if (this._unIndexed) {
  28183. indexToBind = null;
  28184. }
  28185. else {
  28186. switch (fillMode) {
  28187. case BABYLON.Material.PointFillMode:
  28188. indexToBind = null;
  28189. break;
  28190. case BABYLON.Material.WireFrameFillMode:
  28191. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28192. break;
  28193. default:
  28194. case BABYLON.Material.TriangleFillMode:
  28195. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28196. break;
  28197. }
  28198. }
  28199. // VBOs
  28200. this._geometry._bind(effect, indexToBind);
  28201. return this;
  28202. };
  28203. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28204. if (alternate === void 0) { alternate = false; }
  28205. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28206. return this;
  28207. }
  28208. this.onBeforeDrawObservable.notifyObservers(this);
  28209. var scene = this.getScene();
  28210. var engine = scene.getEngine();
  28211. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28212. // or triangles as points
  28213. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28214. }
  28215. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28216. // Triangles as wireframe
  28217. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28218. }
  28219. else {
  28220. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28221. }
  28222. if (scene._isAlternateRenderingEnabled && !alternate) {
  28223. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28224. if (!effect || !scene.activeCamera) {
  28225. return this;
  28226. }
  28227. scene._switchToAlternateCameraConfiguration(true);
  28228. this._effectiveMaterial.bindView(effect);
  28229. this._effectiveMaterial.bindViewProjection(effect);
  28230. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28231. this._draw(subMesh, fillMode, instancesCount, true);
  28232. engine.setViewport(scene.activeCamera.viewport);
  28233. scene._switchToAlternateCameraConfiguration(false);
  28234. this._effectiveMaterial.bindView(effect);
  28235. this._effectiveMaterial.bindViewProjection(effect);
  28236. }
  28237. return this;
  28238. };
  28239. /**
  28240. * Registers for this mesh a javascript function called just before the rendering process.
  28241. * This function is passed the current mesh.
  28242. * Return the Mesh.
  28243. */
  28244. Mesh.prototype.registerBeforeRender = function (func) {
  28245. this.onBeforeRenderObservable.add(func);
  28246. return this;
  28247. };
  28248. /**
  28249. * Disposes a previously registered javascript function called before the rendering.
  28250. * This function is passed the current mesh.
  28251. * Returns the Mesh.
  28252. */
  28253. Mesh.prototype.unregisterBeforeRender = function (func) {
  28254. this.onBeforeRenderObservable.removeCallback(func);
  28255. return this;
  28256. };
  28257. /**
  28258. * Registers for this mesh a javascript function called just after the rendering is complete.
  28259. * This function is passed the current mesh.
  28260. * Returns the Mesh.
  28261. */
  28262. Mesh.prototype.registerAfterRender = function (func) {
  28263. this.onAfterRenderObservable.add(func);
  28264. return this;
  28265. };
  28266. /**
  28267. * Disposes a previously registered javascript function called after the rendering.
  28268. * This function is passed the current mesh.
  28269. * Return the Mesh.
  28270. */
  28271. Mesh.prototype.unregisterAfterRender = function (func) {
  28272. this.onAfterRenderObservable.removeCallback(func);
  28273. return this;
  28274. };
  28275. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28276. var scene = this.getScene();
  28277. this._batchCache.mustReturn = false;
  28278. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28279. this._batchCache.visibleInstances[subMeshId] = null;
  28280. if (this._visibleInstances) {
  28281. var currentRenderId = scene.getRenderId();
  28282. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28283. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28284. var selfRenderId = this._renderId;
  28285. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28286. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28287. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28288. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28289. }
  28290. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28291. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28292. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28293. this._batchCache.mustReturn = true;
  28294. return this._batchCache;
  28295. }
  28296. if (currentRenderId !== selfRenderId) {
  28297. this._batchCache.renderSelf[subMeshId] = false;
  28298. }
  28299. }
  28300. this._renderIdForInstances[subMeshId] = currentRenderId;
  28301. }
  28302. return this._batchCache;
  28303. };
  28304. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28305. var visibleInstances = batch.visibleInstances[subMesh._id];
  28306. if (!visibleInstances) {
  28307. return this;
  28308. }
  28309. var matricesCount = visibleInstances.length + 1;
  28310. var bufferSize = matricesCount * 16 * 4;
  28311. var currentInstancesBufferSize = this._instancesBufferSize;
  28312. var instancesBuffer = this._instancesBuffer;
  28313. while (this._instancesBufferSize < bufferSize) {
  28314. this._instancesBufferSize *= 2;
  28315. }
  28316. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28317. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28318. }
  28319. var offset = 0;
  28320. var instancesCount = 0;
  28321. var world = this.getWorldMatrix();
  28322. if (batch.renderSelf[subMesh._id]) {
  28323. world.copyToArray(this._instancesData, offset);
  28324. offset += 16;
  28325. instancesCount++;
  28326. }
  28327. if (visibleInstances) {
  28328. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28329. var instance = visibleInstances[instanceIndex];
  28330. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28331. offset += 16;
  28332. instancesCount++;
  28333. }
  28334. }
  28335. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28336. if (instancesBuffer) {
  28337. instancesBuffer.dispose();
  28338. }
  28339. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28340. this._instancesBuffer = instancesBuffer;
  28341. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28342. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28343. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28344. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28345. }
  28346. else {
  28347. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28348. }
  28349. this._bind(subMesh, effect, fillMode);
  28350. this._draw(subMesh, fillMode, instancesCount);
  28351. engine.unbindInstanceAttributes();
  28352. return this;
  28353. };
  28354. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28355. var scene = this.getScene();
  28356. var engine = scene.getEngine();
  28357. if (hardwareInstancedRendering) {
  28358. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28359. }
  28360. else {
  28361. if (batch.renderSelf[subMesh._id]) {
  28362. // Draw
  28363. if (onBeforeDraw) {
  28364. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28365. }
  28366. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28367. }
  28368. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28369. if (visibleInstancesForSubMesh) {
  28370. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28371. var instance = visibleInstancesForSubMesh[instanceIndex];
  28372. // World
  28373. var world = instance.getWorldMatrix();
  28374. if (onBeforeDraw) {
  28375. onBeforeDraw(true, world, effectiveMaterial);
  28376. }
  28377. // Draw
  28378. this._draw(subMesh, fillMode);
  28379. }
  28380. }
  28381. }
  28382. return this;
  28383. };
  28384. /**
  28385. * Triggers the draw call for the mesh.
  28386. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28387. * Returns the Mesh.
  28388. */
  28389. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28390. this.checkOcclusionQuery();
  28391. if (this._isOccluded) {
  28392. return this;
  28393. }
  28394. var scene = this.getScene();
  28395. // Managing instances
  28396. var batch = this._getInstancesRenderList(subMesh._id);
  28397. if (batch.mustReturn) {
  28398. return this;
  28399. }
  28400. // Checking geometry state
  28401. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28402. return this;
  28403. }
  28404. this.onBeforeRenderObservable.notifyObservers(this);
  28405. var engine = scene.getEngine();
  28406. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28407. // Material
  28408. var material = subMesh.getMaterial();
  28409. if (!material) {
  28410. return this;
  28411. }
  28412. this._effectiveMaterial = material;
  28413. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28414. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28415. return this;
  28416. }
  28417. }
  28418. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28419. return this;
  28420. }
  28421. // Alpha mode
  28422. if (enableAlphaMode) {
  28423. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28424. }
  28425. // Outline - step 1
  28426. var savedDepthWrite = engine.getDepthWrite();
  28427. if (this.renderOutline) {
  28428. engine.setDepthWrite(false);
  28429. scene.getOutlineRenderer().render(subMesh, batch);
  28430. engine.setDepthWrite(savedDepthWrite);
  28431. }
  28432. var effect;
  28433. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28434. effect = subMesh.effect;
  28435. }
  28436. else {
  28437. effect = this._effectiveMaterial.getEffect();
  28438. }
  28439. if (!effect) {
  28440. return this;
  28441. }
  28442. var sideOrientation = this.overrideMaterialSideOrientation;
  28443. if (sideOrientation == null) {
  28444. sideOrientation = this._effectiveMaterial.sideOrientation;
  28445. if (this._getWorldMatrixDeterminant() < 0) {
  28446. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28447. }
  28448. }
  28449. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28450. if (this._effectiveMaterial.forceDepthWrite) {
  28451. engine.setDepthWrite(true);
  28452. }
  28453. // Bind
  28454. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28455. if (!hardwareInstancedRendering) {
  28456. this._bind(subMesh, effect, fillMode);
  28457. }
  28458. var world = this.getWorldMatrix();
  28459. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28460. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28461. }
  28462. else {
  28463. this._effectiveMaterial.bind(world, this);
  28464. }
  28465. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28466. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28467. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28468. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28469. }
  28470. // Draw
  28471. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28472. // Unbind
  28473. this._effectiveMaterial.unbind();
  28474. // Outline - step 2
  28475. if (this.renderOutline && savedDepthWrite) {
  28476. engine.setDepthWrite(true);
  28477. engine.setColorWrite(false);
  28478. scene.getOutlineRenderer().render(subMesh, batch);
  28479. engine.setColorWrite(true);
  28480. }
  28481. // Overlay
  28482. if (this.renderOverlay) {
  28483. var currentMode = engine.getAlphaMode();
  28484. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28485. scene.getOutlineRenderer().render(subMesh, batch, true);
  28486. engine.setAlphaMode(currentMode);
  28487. }
  28488. this.onAfterRenderObservable.notifyObservers(this);
  28489. return this;
  28490. };
  28491. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28492. if (isInstance && effectiveMaterial) {
  28493. effectiveMaterial.bindOnlyWorldMatrix(world);
  28494. }
  28495. };
  28496. /**
  28497. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28498. */
  28499. Mesh.prototype.getEmittedParticleSystems = function () {
  28500. var results = new Array();
  28501. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28502. var particleSystem = this.getScene().particleSystems[index];
  28503. if (particleSystem.emitter === this) {
  28504. results.push(particleSystem);
  28505. }
  28506. }
  28507. return results;
  28508. };
  28509. /**
  28510. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28511. */
  28512. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28513. var results = new Array();
  28514. var descendants = this.getDescendants();
  28515. descendants.push(this);
  28516. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28517. var particleSystem = this.getScene().particleSystems[index];
  28518. var emitter = particleSystem.emitter;
  28519. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28520. results.push(particleSystem);
  28521. }
  28522. }
  28523. return results;
  28524. };
  28525. Mesh.prototype._checkDelayState = function () {
  28526. var scene = this.getScene();
  28527. if (this._geometry) {
  28528. this._geometry.load(scene);
  28529. }
  28530. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28532. this._queueLoad(scene);
  28533. }
  28534. return this;
  28535. };
  28536. Mesh.prototype._queueLoad = function (scene) {
  28537. var _this = this;
  28538. scene._addPendingData(this);
  28539. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28540. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28541. if (data instanceof ArrayBuffer) {
  28542. _this._delayLoadingFunction(data, _this);
  28543. }
  28544. else {
  28545. _this._delayLoadingFunction(JSON.parse(data), _this);
  28546. }
  28547. _this.instances.forEach(function (instance) {
  28548. instance._syncSubMeshes();
  28549. });
  28550. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28551. scene._removePendingData(_this);
  28552. }, function () { }, scene.database, getBinaryData);
  28553. return this;
  28554. };
  28555. /**
  28556. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28557. */
  28558. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28559. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28560. return false;
  28561. }
  28562. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28563. return false;
  28564. }
  28565. this._checkDelayState();
  28566. return true;
  28567. };
  28568. /**
  28569. * Sets the mesh material by the material or multiMaterial `id` property.
  28570. * The material `id` is a string identifying the material or the multiMaterial.
  28571. * This method returns the Mesh.
  28572. */
  28573. Mesh.prototype.setMaterialByID = function (id) {
  28574. var materials = this.getScene().materials;
  28575. var index;
  28576. for (index = materials.length - 1; index > -1; index--) {
  28577. if (materials[index].id === id) {
  28578. this.material = materials[index];
  28579. return this;
  28580. }
  28581. }
  28582. // Multi
  28583. var multiMaterials = this.getScene().multiMaterials;
  28584. for (index = multiMaterials.length - 1; index > -1; index--) {
  28585. if (multiMaterials[index].id === id) {
  28586. this.material = multiMaterials[index];
  28587. return this;
  28588. }
  28589. }
  28590. return this;
  28591. };
  28592. /**
  28593. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28594. */
  28595. Mesh.prototype.getAnimatables = function () {
  28596. var results = new Array();
  28597. if (this.material) {
  28598. results.push(this.material);
  28599. }
  28600. if (this.skeleton) {
  28601. results.push(this.skeleton);
  28602. }
  28603. return results;
  28604. };
  28605. /**
  28606. * Modifies the mesh geometry according to the passed transformation matrix.
  28607. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28608. * The mesh normals are modified accordingly the same transformation.
  28609. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28610. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28611. * Returns the Mesh.
  28612. */
  28613. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28614. // Position
  28615. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28616. return this;
  28617. }
  28618. var submeshes = this.subMeshes.splice(0);
  28619. this._resetPointsArrayCache();
  28620. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28621. var temp = new Array();
  28622. var index;
  28623. for (index = 0; index < data.length; index += 3) {
  28624. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28625. }
  28626. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28627. // Normals
  28628. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28629. return this;
  28630. }
  28631. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28632. temp = [];
  28633. for (index = 0; index < data.length; index += 3) {
  28634. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28635. }
  28636. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28637. // flip faces?
  28638. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28639. this.flipFaces();
  28640. }
  28641. // Restore submeshes
  28642. this.releaseSubMeshes();
  28643. this.subMeshes = submeshes;
  28644. return this;
  28645. };
  28646. /**
  28647. * Modifies the mesh geometry according to its own current World Matrix.
  28648. * The mesh World Matrix is then reset.
  28649. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28650. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28651. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28652. * Returns the Mesh.
  28653. */
  28654. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28655. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28656. this.scaling.copyFromFloats(1, 1, 1);
  28657. this.position.copyFromFloats(0, 0, 0);
  28658. this.rotation.copyFromFloats(0, 0, 0);
  28659. //only if quaternion is already set
  28660. if (this.rotationQuaternion) {
  28661. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28662. }
  28663. this._worldMatrix = BABYLON.Matrix.Identity();
  28664. return this;
  28665. };
  28666. Object.defineProperty(Mesh.prototype, "_positions", {
  28667. // Cache
  28668. get: function () {
  28669. if (this._geometry) {
  28670. return this._geometry._positions;
  28671. }
  28672. return null;
  28673. },
  28674. enumerable: true,
  28675. configurable: true
  28676. });
  28677. Mesh.prototype._resetPointsArrayCache = function () {
  28678. if (this._geometry) {
  28679. this._geometry._resetPointsArrayCache();
  28680. }
  28681. return this;
  28682. };
  28683. Mesh.prototype._generatePointsArray = function () {
  28684. if (this._geometry) {
  28685. return this._geometry._generatePointsArray();
  28686. }
  28687. return false;
  28688. };
  28689. /**
  28690. * Returns a new Mesh object generated from the current mesh properties.
  28691. * This method must not get confused with createInstance().
  28692. * The parameter `name` is a string, the name given to the new mesh.
  28693. * The optional parameter `newParent` can be any Node object (default `null`).
  28694. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28695. * 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.
  28696. */
  28697. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28698. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28699. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28700. };
  28701. /**
  28702. * Disposes the Mesh.
  28703. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28704. * Returns nothing.
  28705. */
  28706. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28707. var _this = this;
  28708. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28709. this.morphTargetManager = null;
  28710. if (this._geometry) {
  28711. this._geometry.releaseForMesh(this, true);
  28712. }
  28713. // Sources
  28714. var meshes = this.getScene().meshes;
  28715. meshes.forEach(function (abstractMesh) {
  28716. var mesh = abstractMesh;
  28717. if (mesh._source && mesh._source === _this) {
  28718. mesh._source = null;
  28719. }
  28720. });
  28721. this._source = null;
  28722. // Instances
  28723. if (this._instancesBuffer) {
  28724. this._instancesBuffer.dispose();
  28725. this._instancesBuffer = null;
  28726. }
  28727. while (this.instances.length) {
  28728. this.instances[0].dispose();
  28729. }
  28730. // Effect layers.
  28731. var effectLayers = this.getScene().effectLayers;
  28732. for (var i = 0; i < effectLayers.length; i++) {
  28733. var effectLayer = effectLayers[i];
  28734. if (effectLayer) {
  28735. effectLayer._disposeMesh(this);
  28736. }
  28737. }
  28738. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28739. };
  28740. /**
  28741. * Modifies the mesh geometry according to a displacement map.
  28742. * 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.
  28743. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28744. * This method returns nothing.
  28745. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28746. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28747. * 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.
  28748. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28749. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28750. *
  28751. * Returns the Mesh.
  28752. */
  28753. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28754. var _this = this;
  28755. var scene = this.getScene();
  28756. var onload = function (img) {
  28757. // Getting height map data
  28758. var canvas = document.createElement("canvas");
  28759. var context = canvas.getContext("2d");
  28760. var heightMapWidth = img.width;
  28761. var heightMapHeight = img.height;
  28762. canvas.width = heightMapWidth;
  28763. canvas.height = heightMapHeight;
  28764. context.drawImage(img, 0, 0);
  28765. // Create VertexData from map data
  28766. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28767. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28768. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28769. //execute success callback, if set
  28770. if (onSuccess) {
  28771. onSuccess(_this);
  28772. }
  28773. };
  28774. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28775. return this;
  28776. };
  28777. /**
  28778. * Modifies the mesh geometry according to a displacementMap buffer.
  28779. * 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.
  28780. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28781. * This method returns nothing.
  28782. * 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.
  28783. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28784. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28785. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28786. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28787. *
  28788. * Returns the Mesh.
  28789. */
  28790. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28792. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28793. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28794. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28795. return this;
  28796. }
  28797. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28798. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28799. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28800. var position = BABYLON.Vector3.Zero();
  28801. var normal = BABYLON.Vector3.Zero();
  28802. var uv = BABYLON.Vector2.Zero();
  28803. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28804. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28805. for (var index = 0; index < positions.length; index += 3) {
  28806. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28807. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28808. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28809. // Compute height
  28810. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28811. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28812. var pos = (u + v * heightMapWidth) * 4;
  28813. var r = buffer[pos] / 255.0;
  28814. var g = buffer[pos + 1] / 255.0;
  28815. var b = buffer[pos + 2] / 255.0;
  28816. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28817. normal.normalize();
  28818. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28819. position = position.add(normal);
  28820. position.toArray(positions, index);
  28821. }
  28822. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28823. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28824. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28825. return this;
  28826. };
  28827. /**
  28828. * Modify the mesh to get a flat shading rendering.
  28829. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28830. * This method returns the Mesh.
  28831. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28832. */
  28833. Mesh.prototype.convertToFlatShadedMesh = function () {
  28834. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28835. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28836. var kinds = this.getVerticesDataKinds();
  28837. var vbs = {};
  28838. var data = {};
  28839. var newdata = {};
  28840. var updatableNormals = false;
  28841. var kindIndex;
  28842. var kind;
  28843. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28844. kind = kinds[kindIndex];
  28845. var vertexBuffer = this.getVertexBuffer(kind);
  28846. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28847. updatableNormals = vertexBuffer.isUpdatable();
  28848. kinds.splice(kindIndex, 1);
  28849. kindIndex--;
  28850. continue;
  28851. }
  28852. vbs[kind] = vertexBuffer;
  28853. data[kind] = vbs[kind].getData();
  28854. newdata[kind] = [];
  28855. }
  28856. // Save previous submeshes
  28857. var previousSubmeshes = this.subMeshes.slice(0);
  28858. var indices = this.getIndices();
  28859. var totalIndices = this.getTotalIndices();
  28860. // Generating unique vertices per face
  28861. var index;
  28862. for (index = 0; index < totalIndices; index++) {
  28863. var vertexIndex = indices[index];
  28864. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28865. kind = kinds[kindIndex];
  28866. var stride = vbs[kind].getStrideSize();
  28867. for (var offset = 0; offset < stride; offset++) {
  28868. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28869. }
  28870. }
  28871. }
  28872. // Updating faces & normal
  28873. var normals = [];
  28874. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28875. for (index = 0; index < totalIndices; index += 3) {
  28876. indices[index] = index;
  28877. indices[index + 1] = index + 1;
  28878. indices[index + 2] = index + 2;
  28879. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28880. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28881. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28882. var p1p2 = p1.subtract(p2);
  28883. var p3p2 = p3.subtract(p2);
  28884. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28885. // Store same normals for every vertex
  28886. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28887. normals.push(normal.x);
  28888. normals.push(normal.y);
  28889. normals.push(normal.z);
  28890. }
  28891. }
  28892. this.setIndices(indices);
  28893. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28894. // Updating vertex buffers
  28895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28896. kind = kinds[kindIndex];
  28897. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28898. }
  28899. // Updating submeshes
  28900. this.releaseSubMeshes();
  28901. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28902. var previousOne = previousSubmeshes[submeshIndex];
  28903. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28904. }
  28905. this.synchronizeInstances();
  28906. return this;
  28907. };
  28908. /**
  28909. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28910. * In other words, more vertices, no more indices and a single bigger VBO.
  28911. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28912. * Returns the Mesh.
  28913. */
  28914. Mesh.prototype.convertToUnIndexedMesh = function () {
  28915. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28916. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28917. var kinds = this.getVerticesDataKinds();
  28918. var vbs = {};
  28919. var data = {};
  28920. var newdata = {};
  28921. var kindIndex;
  28922. var kind;
  28923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28924. kind = kinds[kindIndex];
  28925. var vertexBuffer = this.getVertexBuffer(kind);
  28926. vbs[kind] = vertexBuffer;
  28927. data[kind] = vbs[kind].getData();
  28928. newdata[kind] = [];
  28929. }
  28930. // Save previous submeshes
  28931. var previousSubmeshes = this.subMeshes.slice(0);
  28932. var indices = this.getIndices();
  28933. var totalIndices = this.getTotalIndices();
  28934. // Generating unique vertices per face
  28935. var index;
  28936. for (index = 0; index < totalIndices; index++) {
  28937. var vertexIndex = indices[index];
  28938. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28939. kind = kinds[kindIndex];
  28940. var stride = vbs[kind].getStrideSize();
  28941. for (var offset = 0; offset < stride; offset++) {
  28942. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28943. }
  28944. }
  28945. }
  28946. // Updating indices
  28947. for (index = 0; index < totalIndices; index += 3) {
  28948. indices[index] = index;
  28949. indices[index + 1] = index + 1;
  28950. indices[index + 2] = index + 2;
  28951. }
  28952. this.setIndices(indices);
  28953. // Updating vertex buffers
  28954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28955. kind = kinds[kindIndex];
  28956. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28957. }
  28958. // Updating submeshes
  28959. this.releaseSubMeshes();
  28960. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28961. var previousOne = previousSubmeshes[submeshIndex];
  28962. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28963. }
  28964. this._unIndexed = true;
  28965. this.synchronizeInstances();
  28966. return this;
  28967. };
  28968. /**
  28969. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28970. * This method returns the Mesh.
  28971. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28972. */
  28973. Mesh.prototype.flipFaces = function (flipNormals) {
  28974. if (flipNormals === void 0) { flipNormals = false; }
  28975. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28976. var i;
  28977. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28978. for (i = 0; i < vertex_data.normals.length; i++) {
  28979. vertex_data.normals[i] *= -1;
  28980. }
  28981. }
  28982. if (vertex_data.indices) {
  28983. var temp;
  28984. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28985. // reassign indices
  28986. temp = vertex_data.indices[i + 1];
  28987. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28988. vertex_data.indices[i + 2] = temp;
  28989. }
  28990. }
  28991. vertex_data.applyToMesh(this);
  28992. return this;
  28993. };
  28994. // Instances
  28995. /**
  28996. * Creates a new InstancedMesh object from the mesh model.
  28997. * An instance shares the same properties and the same material than its model.
  28998. * Only these properties of each instance can then be set individually :
  28999. * - position
  29000. * - rotation
  29001. * - rotationQuaternion
  29002. * - setPivotMatrix
  29003. * - scaling
  29004. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29005. * Warning : this method is not supported for Line mesh and LineSystem
  29006. */
  29007. Mesh.prototype.createInstance = function (name) {
  29008. return new BABYLON.InstancedMesh(name, this);
  29009. };
  29010. /**
  29011. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29012. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29013. * This method returns the Mesh.
  29014. */
  29015. Mesh.prototype.synchronizeInstances = function () {
  29016. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29017. var instance = this.instances[instanceIndex];
  29018. instance._syncSubMeshes();
  29019. }
  29020. return this;
  29021. };
  29022. /**
  29023. * Simplify the mesh according to the given array of settings.
  29024. * Function will return immediately and will simplify async. It returns the Mesh.
  29025. * @param settings a collection of simplification settings.
  29026. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29027. * @param type the type of simplification to run.
  29028. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29029. */
  29030. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29031. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29032. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29033. this.getScene().simplificationQueue.addTask({
  29034. settings: settings,
  29035. parallelProcessing: parallelProcessing,
  29036. mesh: this,
  29037. simplificationType: simplificationType,
  29038. successCallback: successCallback
  29039. });
  29040. return this;
  29041. };
  29042. /**
  29043. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29044. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29045. * This should be used together with the simplification to avoid disappearing triangles.
  29046. * Returns the Mesh.
  29047. * @param successCallback an optional success callback to be called after the optimization finished.
  29048. */
  29049. Mesh.prototype.optimizeIndices = function (successCallback) {
  29050. var _this = this;
  29051. var indices = this.getIndices();
  29052. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29053. if (!positions || !indices) {
  29054. return this;
  29055. }
  29056. var vectorPositions = new Array();
  29057. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29058. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29059. }
  29060. var dupes = new Array();
  29061. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29062. var realPos = vectorPositions.length - 1 - iteration;
  29063. var testedPosition = vectorPositions[realPos];
  29064. for (var j = 0; j < realPos; ++j) {
  29065. var againstPosition = vectorPositions[j];
  29066. if (testedPosition.equals(againstPosition)) {
  29067. dupes[realPos] = j;
  29068. break;
  29069. }
  29070. }
  29071. }, function () {
  29072. for (var i = 0; i < indices.length; ++i) {
  29073. indices[i] = dupes[indices[i]] || indices[i];
  29074. }
  29075. //indices are now reordered
  29076. var originalSubMeshes = _this.subMeshes.slice(0);
  29077. _this.setIndices(indices);
  29078. _this.subMeshes = originalSubMeshes;
  29079. if (successCallback) {
  29080. successCallback(_this);
  29081. }
  29082. });
  29083. return this;
  29084. };
  29085. Mesh.prototype.serialize = function (serializationObject) {
  29086. serializationObject.name = this.name;
  29087. serializationObject.id = this.id;
  29088. serializationObject.type = this.getClassName();
  29089. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29090. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29091. }
  29092. serializationObject.position = this.position.asArray();
  29093. if (this.rotationQuaternion) {
  29094. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29095. }
  29096. else if (this.rotation) {
  29097. serializationObject.rotation = this.rotation.asArray();
  29098. }
  29099. serializationObject.scaling = this.scaling.asArray();
  29100. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29101. serializationObject.isEnabled = this.isEnabled(false);
  29102. serializationObject.isVisible = this.isVisible;
  29103. serializationObject.infiniteDistance = this.infiniteDistance;
  29104. serializationObject.pickable = this.isPickable;
  29105. serializationObject.receiveShadows = this.receiveShadows;
  29106. serializationObject.billboardMode = this.billboardMode;
  29107. serializationObject.visibility = this.visibility;
  29108. serializationObject.checkCollisions = this.checkCollisions;
  29109. serializationObject.isBlocker = this.isBlocker;
  29110. // Parent
  29111. if (this.parent) {
  29112. serializationObject.parentId = this.parent.id;
  29113. }
  29114. // Geometry
  29115. serializationObject.isUnIndexed = this.isUnIndexed;
  29116. var geometry = this._geometry;
  29117. if (geometry) {
  29118. var geometryId = geometry.id;
  29119. serializationObject.geometryId = geometryId;
  29120. // SubMeshes
  29121. serializationObject.subMeshes = [];
  29122. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29123. var subMesh = this.subMeshes[subIndex];
  29124. serializationObject.subMeshes.push({
  29125. materialIndex: subMesh.materialIndex,
  29126. verticesStart: subMesh.verticesStart,
  29127. verticesCount: subMesh.verticesCount,
  29128. indexStart: subMesh.indexStart,
  29129. indexCount: subMesh.indexCount
  29130. });
  29131. }
  29132. }
  29133. // Material
  29134. if (this.material) {
  29135. serializationObject.materialId = this.material.id;
  29136. }
  29137. else {
  29138. this.material = null;
  29139. }
  29140. // Morph targets
  29141. if (this.morphTargetManager) {
  29142. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29143. }
  29144. // Skeleton
  29145. if (this.skeleton) {
  29146. serializationObject.skeletonId = this.skeleton.id;
  29147. }
  29148. // Physics
  29149. //TODO implement correct serialization for physics impostors.
  29150. var impostor = this.getPhysicsImpostor();
  29151. if (impostor) {
  29152. serializationObject.physicsMass = impostor.getParam("mass");
  29153. serializationObject.physicsFriction = impostor.getParam("friction");
  29154. serializationObject.physicsRestitution = impostor.getParam("mass");
  29155. serializationObject.physicsImpostor = impostor.type;
  29156. }
  29157. // Metadata
  29158. if (this.metadata) {
  29159. serializationObject.metadata = this.metadata;
  29160. }
  29161. // Instances
  29162. serializationObject.instances = [];
  29163. for (var index = 0; index < this.instances.length; index++) {
  29164. var instance = this.instances[index];
  29165. var serializationInstance = {
  29166. name: instance.name,
  29167. id: instance.id,
  29168. position: instance.position.asArray(),
  29169. scaling: instance.scaling.asArray()
  29170. };
  29171. if (instance.rotationQuaternion) {
  29172. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29173. }
  29174. else if (instance.rotation) {
  29175. serializationInstance.rotation = instance.rotation.asArray();
  29176. }
  29177. serializationObject.instances.push(serializationInstance);
  29178. // Animations
  29179. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29180. serializationInstance.ranges = instance.serializeAnimationRanges();
  29181. }
  29182. //
  29183. // Animations
  29184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29185. serializationObject.ranges = this.serializeAnimationRanges();
  29186. // Layer mask
  29187. serializationObject.layerMask = this.layerMask;
  29188. // Alpha
  29189. serializationObject.alphaIndex = this.alphaIndex;
  29190. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29191. // Overlay
  29192. serializationObject.overlayAlpha = this.overlayAlpha;
  29193. serializationObject.overlayColor = this.overlayColor.asArray();
  29194. serializationObject.renderOverlay = this.renderOverlay;
  29195. // Fog
  29196. serializationObject.applyFog = this.applyFog;
  29197. // Action Manager
  29198. if (this.actionManager) {
  29199. serializationObject.actions = this.actionManager.serialize(this.name);
  29200. }
  29201. };
  29202. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29203. if (!this.geometry) {
  29204. return;
  29205. }
  29206. this._markSubMeshesAsAttributesDirty();
  29207. var morphTargetManager = this._morphTargetManager;
  29208. if (morphTargetManager && morphTargetManager.vertexCount) {
  29209. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29210. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29211. this.morphTargetManager = null;
  29212. return;
  29213. }
  29214. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29215. var morphTarget = morphTargetManager.getActiveTarget(index);
  29216. var positions = morphTarget.getPositions();
  29217. if (!positions) {
  29218. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29219. return;
  29220. }
  29221. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29222. var normals = morphTarget.getNormals();
  29223. if (normals) {
  29224. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29225. }
  29226. var tangents = morphTarget.getTangents();
  29227. if (tangents) {
  29228. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29229. }
  29230. }
  29231. }
  29232. else {
  29233. var index = 0;
  29234. // Positions
  29235. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29236. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29237. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29238. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29239. }
  29240. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29241. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29242. }
  29243. index++;
  29244. }
  29245. }
  29246. };
  29247. // Statics
  29248. /**
  29249. * Returns a new Mesh object parsed from the source provided.
  29250. * The parameter `parsedMesh` is the source.
  29251. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29252. */
  29253. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29254. var mesh;
  29255. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29256. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29257. }
  29258. else {
  29259. mesh = new Mesh(parsedMesh.name, scene);
  29260. }
  29261. mesh.id = parsedMesh.id;
  29262. if (BABYLON.Tags) {
  29263. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29264. }
  29265. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29266. if (parsedMesh.metadata !== undefined) {
  29267. mesh.metadata = parsedMesh.metadata;
  29268. }
  29269. if (parsedMesh.rotationQuaternion) {
  29270. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29271. }
  29272. else if (parsedMesh.rotation) {
  29273. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29274. }
  29275. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29276. if (parsedMesh.localMatrix) {
  29277. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29278. }
  29279. else if (parsedMesh.pivotMatrix) {
  29280. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29281. }
  29282. mesh.setEnabled(parsedMesh.isEnabled);
  29283. mesh.isVisible = parsedMesh.isVisible;
  29284. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29285. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29286. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29287. if (parsedMesh.applyFog !== undefined) {
  29288. mesh.applyFog = parsedMesh.applyFog;
  29289. }
  29290. if (parsedMesh.pickable !== undefined) {
  29291. mesh.isPickable = parsedMesh.pickable;
  29292. }
  29293. if (parsedMesh.alphaIndex !== undefined) {
  29294. mesh.alphaIndex = parsedMesh.alphaIndex;
  29295. }
  29296. mesh.receiveShadows = parsedMesh.receiveShadows;
  29297. mesh.billboardMode = parsedMesh.billboardMode;
  29298. if (parsedMesh.visibility !== undefined) {
  29299. mesh.visibility = parsedMesh.visibility;
  29300. }
  29301. mesh.checkCollisions = parsedMesh.checkCollisions;
  29302. if (parsedMesh.isBlocker !== undefined) {
  29303. mesh.isBlocker = parsedMesh.isBlocker;
  29304. }
  29305. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29306. // freezeWorldMatrix
  29307. if (parsedMesh.freezeWorldMatrix) {
  29308. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29309. }
  29310. // Parent
  29311. if (parsedMesh.parentId) {
  29312. mesh._waitingParentId = parsedMesh.parentId;
  29313. }
  29314. // Actions
  29315. if (parsedMesh.actions !== undefined) {
  29316. mesh._waitingActions = parsedMesh.actions;
  29317. }
  29318. // Overlay
  29319. if (parsedMesh.overlayAlpha !== undefined) {
  29320. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29321. }
  29322. if (parsedMesh.overlayColor !== undefined) {
  29323. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29324. }
  29325. if (parsedMesh.renderOverlay !== undefined) {
  29326. mesh.renderOverlay = parsedMesh.renderOverlay;
  29327. }
  29328. // Geometry
  29329. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29330. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29331. if (parsedMesh.delayLoadingFile) {
  29332. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29333. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29334. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29335. if (parsedMesh._binaryInfo) {
  29336. mesh._binaryInfo = parsedMesh._binaryInfo;
  29337. }
  29338. mesh._delayInfo = [];
  29339. if (parsedMesh.hasUVs) {
  29340. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29341. }
  29342. if (parsedMesh.hasUVs2) {
  29343. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29344. }
  29345. if (parsedMesh.hasUVs3) {
  29346. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29347. }
  29348. if (parsedMesh.hasUVs4) {
  29349. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29350. }
  29351. if (parsedMesh.hasUVs5) {
  29352. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29353. }
  29354. if (parsedMesh.hasUVs6) {
  29355. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29356. }
  29357. if (parsedMesh.hasColors) {
  29358. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29359. }
  29360. if (parsedMesh.hasMatricesIndices) {
  29361. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29362. }
  29363. if (parsedMesh.hasMatricesWeights) {
  29364. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29365. }
  29366. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29367. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29368. mesh._checkDelayState();
  29369. }
  29370. }
  29371. else {
  29372. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29373. }
  29374. // Material
  29375. if (parsedMesh.materialId) {
  29376. mesh.setMaterialByID(parsedMesh.materialId);
  29377. }
  29378. else {
  29379. mesh.material = null;
  29380. }
  29381. // Morph targets
  29382. if (parsedMesh.morphTargetManagerId > -1) {
  29383. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29384. }
  29385. // Skeleton
  29386. if (parsedMesh.skeletonId > -1) {
  29387. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29388. if (parsedMesh.numBoneInfluencers) {
  29389. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29390. }
  29391. }
  29392. // Animations
  29393. if (parsedMesh.animations) {
  29394. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29395. var parsedAnimation = parsedMesh.animations[animationIndex];
  29396. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29397. }
  29398. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29399. }
  29400. if (parsedMesh.autoAnimate) {
  29401. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29402. }
  29403. // Layer Mask
  29404. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29405. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29406. }
  29407. else {
  29408. mesh.layerMask = 0x0FFFFFFF;
  29409. }
  29410. // Physics
  29411. if (parsedMesh.physicsImpostor) {
  29412. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29413. mass: parsedMesh.physicsMass,
  29414. friction: parsedMesh.physicsFriction,
  29415. restitution: parsedMesh.physicsRestitution
  29416. }, scene);
  29417. }
  29418. // Instances
  29419. if (parsedMesh.instances) {
  29420. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29421. var parsedInstance = parsedMesh.instances[index];
  29422. var instance = mesh.createInstance(parsedInstance.name);
  29423. if (parsedInstance.id) {
  29424. instance.id = parsedInstance.id;
  29425. }
  29426. if (BABYLON.Tags) {
  29427. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29428. }
  29429. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29430. if (parsedInstance.parentId) {
  29431. instance._waitingParentId = parsedInstance.parentId;
  29432. }
  29433. if (parsedInstance.rotationQuaternion) {
  29434. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29435. }
  29436. else if (parsedInstance.rotation) {
  29437. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29438. }
  29439. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29440. instance.checkCollisions = mesh.checkCollisions;
  29441. if (parsedMesh.animations) {
  29442. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29443. parsedAnimation = parsedMesh.animations[animationIndex];
  29444. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29445. }
  29446. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29447. }
  29448. }
  29449. }
  29450. return mesh;
  29451. };
  29452. /**
  29453. * Creates a ribbon mesh.
  29454. * Please consider using the same method from the MeshBuilder class instead.
  29455. * 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.
  29456. *
  29457. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29458. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29459. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29460. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29461. * 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.
  29462. * 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.
  29463. * 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
  29464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29467. */
  29468. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29469. if (closeArray === void 0) { closeArray = false; }
  29470. if (updatable === void 0) { updatable = false; }
  29471. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29472. pathArray: pathArray,
  29473. closeArray: closeArray,
  29474. closePath: closePath,
  29475. offset: offset,
  29476. updatable: updatable,
  29477. sideOrientation: sideOrientation,
  29478. instance: instance
  29479. }, scene);
  29480. };
  29481. /**
  29482. * Creates a plane polygonal mesh. By default, this is a disc.
  29483. * Please consider using the same method from the MeshBuilder class instead.
  29484. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29485. * 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.
  29486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29489. */
  29490. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29491. if (scene === void 0) { scene = null; }
  29492. var options = {
  29493. radius: radius,
  29494. tessellation: tessellation,
  29495. sideOrientation: sideOrientation,
  29496. updatable: updatable
  29497. };
  29498. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29499. };
  29500. /**
  29501. * Creates a box mesh.
  29502. * Please consider using the same method from the MeshBuilder class instead.
  29503. * The parameter `size` sets the size (float) of each box side (default 1).
  29504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29507. */
  29508. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29509. if (scene === void 0) { scene = null; }
  29510. var options = {
  29511. size: size,
  29512. sideOrientation: sideOrientation,
  29513. updatable: updatable
  29514. };
  29515. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29516. };
  29517. /**
  29518. * Creates a sphere mesh.
  29519. * Please consider using the same method from the MeshBuilder class instead.
  29520. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29521. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29525. */
  29526. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29527. var options = {
  29528. segments: segments,
  29529. diameterX: diameter,
  29530. diameterY: diameter,
  29531. diameterZ: diameter,
  29532. sideOrientation: sideOrientation,
  29533. updatable: updatable
  29534. };
  29535. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29536. };
  29537. /**
  29538. * Creates a cylinder or a cone mesh.
  29539. * Please consider using the same method from the MeshBuilder class instead.
  29540. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29541. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29542. * 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.
  29543. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29544. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29548. */
  29549. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29550. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29551. if (scene !== undefined) {
  29552. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29553. updatable = scene;
  29554. }
  29555. scene = subdivisions;
  29556. subdivisions = 1;
  29557. }
  29558. var options = {
  29559. height: height,
  29560. diameterTop: diameterTop,
  29561. diameterBottom: diameterBottom,
  29562. tessellation: tessellation,
  29563. subdivisions: subdivisions,
  29564. sideOrientation: sideOrientation,
  29565. updatable: updatable
  29566. };
  29567. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29568. };
  29569. // Torus (Code from SharpDX.org)
  29570. /**
  29571. * Creates a torus mesh.
  29572. * Please consider using the same method from the MeshBuilder class instead.
  29573. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29574. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29575. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29579. */
  29580. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29581. var options = {
  29582. diameter: diameter,
  29583. thickness: thickness,
  29584. tessellation: tessellation,
  29585. sideOrientation: sideOrientation,
  29586. updatable: updatable
  29587. };
  29588. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29589. };
  29590. /**
  29591. * Creates a torus knot mesh.
  29592. * Please consider using the same method from the MeshBuilder class instead.
  29593. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29594. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29595. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29596. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29598. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29600. */
  29601. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29602. var options = {
  29603. radius: radius,
  29604. tube: tube,
  29605. radialSegments: radialSegments,
  29606. tubularSegments: tubularSegments,
  29607. p: p,
  29608. q: q,
  29609. sideOrientation: sideOrientation,
  29610. updatable: updatable
  29611. };
  29612. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29613. };
  29614. /**
  29615. * Creates a line mesh.
  29616. * Please consider using the same method from the MeshBuilder class instead.
  29617. * 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.
  29618. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29619. * The parameter `points` is an array successive Vector3.
  29620. * 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
  29621. * When updating an instance, remember that only point positions can change, not the number of points.
  29622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29623. */
  29624. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29625. if (scene === void 0) { scene = null; }
  29626. if (updatable === void 0) { updatable = false; }
  29627. if (instance === void 0) { instance = null; }
  29628. var options = {
  29629. points: points,
  29630. updatable: updatable,
  29631. instance: instance
  29632. };
  29633. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates a dashed line mesh.
  29637. * Please consider using the same method from the MeshBuilder class instead.
  29638. * 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.
  29639. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29640. * The parameter `points` is an array successive Vector3.
  29641. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29642. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29643. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29644. * 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
  29645. * When updating an instance, remember that only point positions can change, not the number of points.
  29646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29647. */
  29648. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29649. if (scene === void 0) { scene = null; }
  29650. var options = {
  29651. points: points,
  29652. dashSize: dashSize,
  29653. gapSize: gapSize,
  29654. dashNb: dashNb,
  29655. updatable: updatable,
  29656. instance: instance
  29657. };
  29658. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29659. };
  29660. /**
  29661. * Creates a polygon mesh.
  29662. * Please consider using the same method from the MeshBuilder class instead.
  29663. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29664. * 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.
  29665. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29667. * Remember you can only change the shape positions, not their number when updating a polygon.
  29668. */
  29669. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29670. var options = {
  29671. shape: shape,
  29672. holes: holes,
  29673. updatable: updatable,
  29674. sideOrientation: sideOrientation
  29675. };
  29676. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29677. };
  29678. /**
  29679. * Creates an extruded polygon mesh, with depth in the Y direction.
  29680. * Please consider using the same method from the MeshBuilder class instead.
  29681. */
  29682. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29683. var options = {
  29684. shape: shape,
  29685. holes: holes,
  29686. depth: depth,
  29687. updatable: updatable,
  29688. sideOrientation: sideOrientation
  29689. };
  29690. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29691. };
  29692. /**
  29693. * Creates an extruded shape mesh.
  29694. * 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.
  29695. * Please consider using the same method from the MeshBuilder class instead.
  29696. *
  29697. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29698. * 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
  29699. * extruded along the Z axis.
  29700. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29701. * 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.
  29702. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29703. * 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
  29704. * 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
  29705. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29709. */
  29710. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29711. if (scene === void 0) { scene = null; }
  29712. var options = {
  29713. shape: shape,
  29714. path: path,
  29715. scale: scale,
  29716. rotation: rotation,
  29717. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29718. sideOrientation: sideOrientation,
  29719. instance: instance,
  29720. updatable: updatable
  29721. };
  29722. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29723. };
  29724. /**
  29725. * Creates an custom extruded shape mesh.
  29726. * 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.
  29727. * Please consider using the same method from the MeshBuilder class instead.
  29728. *
  29729. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29730. * 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
  29731. * extruded along the Z axis.
  29732. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29733. * 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
  29734. * and the distance of this point from the begining of the path :
  29735. * ```javascript
  29736. * var rotationFunction = function(i, distance) {
  29737. * // do things
  29738. * return rotationValue; }
  29739. * ```
  29740. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29741. * 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
  29742. * and the distance of this point from the begining of the path :
  29743. * ```javascript
  29744. * var scaleFunction = function(i, distance) {
  29745. * // do things
  29746. * return scaleValue;}
  29747. * ```
  29748. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29749. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29750. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29751. * 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
  29752. * 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
  29753. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29757. */
  29758. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29759. var options = {
  29760. shape: shape,
  29761. path: path,
  29762. scaleFunction: scaleFunction,
  29763. rotationFunction: rotationFunction,
  29764. ribbonCloseArray: ribbonCloseArray,
  29765. ribbonClosePath: ribbonClosePath,
  29766. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29767. sideOrientation: sideOrientation,
  29768. instance: instance,
  29769. updatable: updatable
  29770. };
  29771. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29772. };
  29773. /**
  29774. * Creates lathe mesh.
  29775. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29776. * Please consider using the same method from the MeshBuilder class instead.
  29777. * 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
  29778. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29779. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29780. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29784. */
  29785. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29786. var options = {
  29787. shape: shape,
  29788. radius: radius,
  29789. tessellation: tessellation,
  29790. sideOrientation: sideOrientation,
  29791. updatable: updatable
  29792. };
  29793. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29794. };
  29795. /**
  29796. * Creates a plane mesh.
  29797. * Please consider using the same method from the MeshBuilder class instead.
  29798. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29800. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29802. */
  29803. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29804. var options = {
  29805. size: size,
  29806. width: size,
  29807. height: size,
  29808. sideOrientation: sideOrientation,
  29809. updatable: updatable
  29810. };
  29811. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29812. };
  29813. /**
  29814. * Creates a ground mesh.
  29815. * Please consider using the same method from the MeshBuilder class instead.
  29816. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29817. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29819. */
  29820. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29821. var options = {
  29822. width: width,
  29823. height: height,
  29824. subdivisions: subdivisions,
  29825. updatable: updatable
  29826. };
  29827. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29828. };
  29829. /**
  29830. * Creates a tiled ground mesh.
  29831. * Please consider using the same method from the MeshBuilder class instead.
  29832. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29833. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29834. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29835. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29836. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29837. * numbers of subdivisions on the ground width and height of each tile.
  29838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29839. */
  29840. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29841. var options = {
  29842. xmin: xmin,
  29843. zmin: zmin,
  29844. xmax: xmax,
  29845. zmax: zmax,
  29846. subdivisions: subdivisions,
  29847. precision: precision,
  29848. updatable: updatable
  29849. };
  29850. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29851. };
  29852. /**
  29853. * Creates a ground mesh from a height map.
  29854. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29855. * Please consider using the same method from the MeshBuilder class instead.
  29856. * The parameter `url` sets the URL of the height map image resource.
  29857. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29858. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29859. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29860. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29861. * 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).
  29862. * This function is passed the newly built mesh :
  29863. * ```javascript
  29864. * function(mesh) { // do things
  29865. * return; }
  29866. * ```
  29867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29868. */
  29869. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29870. var options = {
  29871. width: width,
  29872. height: height,
  29873. subdivisions: subdivisions,
  29874. minHeight: minHeight,
  29875. maxHeight: maxHeight,
  29876. updatable: updatable,
  29877. onReady: onReady
  29878. };
  29879. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29880. };
  29881. /**
  29882. * Creates a tube mesh.
  29883. * 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.
  29884. * Please consider using the same method from the MeshBuilder class instead.
  29885. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29886. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29887. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29888. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29889. * 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.
  29890. * It must return a radius value (positive float) :
  29891. * ```javascript
  29892. * var radiusFunction = function(i, distance) {
  29893. * // do things
  29894. * return radius; }
  29895. * ```
  29896. * 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
  29897. * 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
  29898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29899. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29901. */
  29902. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29903. var options = {
  29904. path: path,
  29905. radius: radius,
  29906. tessellation: tessellation,
  29907. radiusFunction: radiusFunction,
  29908. arc: 1,
  29909. cap: cap,
  29910. updatable: updatable,
  29911. sideOrientation: sideOrientation,
  29912. instance: instance
  29913. };
  29914. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29915. };
  29916. /**
  29917. * Creates a polyhedron mesh.
  29918. * Please consider using the same method from the MeshBuilder class instead.
  29919. * 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
  29920. * to choose the wanted type.
  29921. * The parameter `size` (positive float, default 1) sets the polygon size.
  29922. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29923. * 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`.
  29924. * 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
  29925. * 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)`).
  29926. * 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
  29927. * 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.
  29928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29929. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29931. */
  29932. Mesh.CreatePolyhedron = function (name, options, scene) {
  29933. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29934. };
  29935. /**
  29936. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29937. * Please consider using the same method from the MeshBuilder class instead.
  29938. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29939. * 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`).
  29940. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29941. * 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.
  29942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29945. */
  29946. Mesh.CreateIcoSphere = function (name, options, scene) {
  29947. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29948. };
  29949. /**
  29950. * Creates a decal mesh.
  29951. * Please consider using the same method from the MeshBuilder class instead.
  29952. * 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.
  29953. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29954. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29955. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29956. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29957. */
  29958. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29959. var options = {
  29960. position: position,
  29961. normal: normal,
  29962. size: size,
  29963. angle: angle
  29964. };
  29965. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29966. };
  29967. // Skeletons
  29968. /**
  29969. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29970. */
  29971. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29972. if (!this._sourcePositions) {
  29973. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29974. if (!source) {
  29975. return this._sourcePositions;
  29976. }
  29977. this._sourcePositions = new Float32Array(source);
  29978. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29979. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29980. }
  29981. }
  29982. return this._sourcePositions;
  29983. };
  29984. /**
  29985. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29986. */
  29987. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29988. if (!this._sourceNormals) {
  29989. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29990. if (!source) {
  29991. return this._sourceNormals;
  29992. }
  29993. this._sourceNormals = new Float32Array(source);
  29994. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29995. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29996. }
  29997. }
  29998. return this._sourceNormals;
  29999. };
  30000. /**
  30001. * Updates the vertex buffer by applying transformation from the bones.
  30002. * Returns the Mesh.
  30003. *
  30004. * @param {skeleton} skeleton to apply
  30005. */
  30006. Mesh.prototype.applySkeleton = function (skeleton) {
  30007. if (!this.geometry) {
  30008. return this;
  30009. }
  30010. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30011. return this;
  30012. }
  30013. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30014. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30015. return this;
  30016. }
  30017. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30018. return this;
  30019. }
  30020. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30021. return this;
  30022. }
  30023. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30024. return this;
  30025. }
  30026. if (!this._sourcePositions) {
  30027. var submeshes = this.subMeshes.slice();
  30028. this.setPositionsForCPUSkinning();
  30029. this.subMeshes = submeshes;
  30030. }
  30031. if (!this._sourceNormals) {
  30032. this.setNormalsForCPUSkinning();
  30033. }
  30034. // positionsData checks for not being Float32Array will only pass at most once
  30035. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30036. if (!positionsData) {
  30037. return this;
  30038. }
  30039. if (!(positionsData instanceof Float32Array)) {
  30040. positionsData = new Float32Array(positionsData);
  30041. }
  30042. // normalsData checks for not being Float32Array will only pass at most once
  30043. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30044. if (!normalsData) {
  30045. return this;
  30046. }
  30047. if (!(normalsData instanceof Float32Array)) {
  30048. normalsData = new Float32Array(normalsData);
  30049. }
  30050. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30051. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30052. if (!matricesWeightsData || !matricesIndicesData) {
  30053. return this;
  30054. }
  30055. var needExtras = this.numBoneInfluencers > 4;
  30056. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30057. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30058. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30059. var tempVector3 = BABYLON.Vector3.Zero();
  30060. var finalMatrix = new BABYLON.Matrix();
  30061. var tempMatrix = new BABYLON.Matrix();
  30062. var matWeightIdx = 0;
  30063. var inf;
  30064. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30065. var weight;
  30066. for (inf = 0; inf < 4; inf++) {
  30067. weight = matricesWeightsData[matWeightIdx + inf];
  30068. if (weight > 0) {
  30069. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30070. finalMatrix.addToSelf(tempMatrix);
  30071. }
  30072. else
  30073. break;
  30074. }
  30075. if (needExtras) {
  30076. for (inf = 0; inf < 4; inf++) {
  30077. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30078. if (weight > 0) {
  30079. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30080. finalMatrix.addToSelf(tempMatrix);
  30081. }
  30082. else
  30083. break;
  30084. }
  30085. }
  30086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30087. tempVector3.toArray(positionsData, index);
  30088. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30089. tempVector3.toArray(normalsData, index);
  30090. finalMatrix.reset();
  30091. }
  30092. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30093. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30094. return this;
  30095. };
  30096. // Tools
  30097. /**
  30098. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30099. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30100. */
  30101. Mesh.MinMax = function (meshes) {
  30102. var minVector = null;
  30103. var maxVector = null;
  30104. meshes.forEach(function (mesh, index, array) {
  30105. var boundingInfo = mesh.getBoundingInfo();
  30106. var boundingBox = boundingInfo.boundingBox;
  30107. if (!minVector || !maxVector) {
  30108. minVector = boundingBox.minimumWorld;
  30109. maxVector = boundingBox.maximumWorld;
  30110. }
  30111. else {
  30112. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30113. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30114. }
  30115. });
  30116. if (!minVector || !maxVector) {
  30117. return {
  30118. min: BABYLON.Vector3.Zero(),
  30119. max: BABYLON.Vector3.Zero()
  30120. };
  30121. }
  30122. return {
  30123. min: minVector,
  30124. max: maxVector
  30125. };
  30126. };
  30127. /**
  30128. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30129. */
  30130. Mesh.Center = function (meshesOrMinMaxVector) {
  30131. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30132. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30133. };
  30134. /**
  30135. * Merge the array of meshes into a single mesh for performance reasons.
  30136. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30137. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30138. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30139. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30140. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30141. */
  30142. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30143. if (disposeSource === void 0) { disposeSource = true; }
  30144. var index;
  30145. if (!allow32BitsIndices) {
  30146. var totalVertices = 0;
  30147. // Counting vertices
  30148. for (index = 0; index < meshes.length; index++) {
  30149. if (meshes[index]) {
  30150. totalVertices += meshes[index].getTotalVertices();
  30151. if (totalVertices > 65536) {
  30152. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30153. return null;
  30154. }
  30155. }
  30156. }
  30157. }
  30158. // Merge
  30159. var vertexData = null;
  30160. var otherVertexData;
  30161. var indiceArray = new Array();
  30162. var source = null;
  30163. for (index = 0; index < meshes.length; index++) {
  30164. if (meshes[index]) {
  30165. meshes[index].computeWorldMatrix(true);
  30166. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30167. otherVertexData.transform(meshes[index].getWorldMatrix());
  30168. if (vertexData) {
  30169. vertexData.merge(otherVertexData);
  30170. }
  30171. else {
  30172. vertexData = otherVertexData;
  30173. source = meshes[index];
  30174. }
  30175. if (subdivideWithSubMeshes) {
  30176. indiceArray.push(meshes[index].getTotalIndices());
  30177. }
  30178. }
  30179. }
  30180. source = source;
  30181. if (!meshSubclass) {
  30182. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30183. }
  30184. vertexData.applyToMesh(meshSubclass);
  30185. // Setting properties
  30186. meshSubclass.material = source.material;
  30187. meshSubclass.checkCollisions = source.checkCollisions;
  30188. // Cleaning
  30189. if (disposeSource) {
  30190. for (index = 0; index < meshes.length; index++) {
  30191. if (meshes[index]) {
  30192. meshes[index].dispose();
  30193. }
  30194. }
  30195. }
  30196. // Subdivide
  30197. if (subdivideWithSubMeshes) {
  30198. //-- Suppresions du submesh global
  30199. meshSubclass.releaseSubMeshes();
  30200. index = 0;
  30201. var offset = 0;
  30202. //-- aplique la subdivision en fonction du tableau d'indices
  30203. while (index < indiceArray.length) {
  30204. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30205. offset += indiceArray[index];
  30206. index++;
  30207. }
  30208. }
  30209. return meshSubclass;
  30210. };
  30211. // Consts
  30212. Mesh._FRONTSIDE = 0;
  30213. Mesh._BACKSIDE = 1;
  30214. Mesh._DOUBLESIDE = 2;
  30215. Mesh._DEFAULTSIDE = 0;
  30216. Mesh._NO_CAP = 0;
  30217. Mesh._CAP_START = 1;
  30218. Mesh._CAP_END = 2;
  30219. Mesh._CAP_ALL = 3;
  30220. return Mesh;
  30221. }(BABYLON.AbstractMesh));
  30222. BABYLON.Mesh = Mesh;
  30223. })(BABYLON || (BABYLON = {}));
  30224. //# sourceMappingURL=babylon.mesh.js.map
  30225. var BABYLON;
  30226. (function (BABYLON) {
  30227. var BaseSubMesh = /** @class */ (function () {
  30228. function BaseSubMesh() {
  30229. }
  30230. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30231. get: function () {
  30232. return this._materialEffect;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30238. if (defines === void 0) { defines = null; }
  30239. if (this._materialEffect === effect) {
  30240. if (!effect) {
  30241. this._materialDefines = null;
  30242. }
  30243. return;
  30244. }
  30245. this._materialDefines = defines;
  30246. this._materialEffect = effect;
  30247. };
  30248. return BaseSubMesh;
  30249. }());
  30250. BABYLON.BaseSubMesh = BaseSubMesh;
  30251. var SubMesh = /** @class */ (function (_super) {
  30252. __extends(SubMesh, _super);
  30253. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30254. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30255. var _this = _super.call(this) || this;
  30256. _this.materialIndex = materialIndex;
  30257. _this.verticesStart = verticesStart;
  30258. _this.verticesCount = verticesCount;
  30259. _this.indexStart = indexStart;
  30260. _this.indexCount = indexCount;
  30261. _this._renderId = 0;
  30262. _this._mesh = mesh;
  30263. _this._renderingMesh = renderingMesh || mesh;
  30264. mesh.subMeshes.push(_this);
  30265. _this._trianglePlanes = [];
  30266. _this._id = mesh.subMeshes.length - 1;
  30267. if (createBoundingBox) {
  30268. _this.refreshBoundingInfo();
  30269. mesh.computeWorldMatrix(true);
  30270. }
  30271. return _this;
  30272. }
  30273. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30274. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30275. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30276. };
  30277. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30278. get: function () {
  30279. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. /**
  30285. * Returns the submesh BoudingInfo object.
  30286. */
  30287. SubMesh.prototype.getBoundingInfo = function () {
  30288. if (this.IsGlobal) {
  30289. return this._mesh.getBoundingInfo();
  30290. }
  30291. return this._boundingInfo;
  30292. };
  30293. /**
  30294. * Sets the submesh BoundingInfo.
  30295. * Return the SubMesh.
  30296. */
  30297. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30298. this._boundingInfo = boundingInfo;
  30299. return this;
  30300. };
  30301. /**
  30302. * Returns the mesh of the current submesh.
  30303. */
  30304. SubMesh.prototype.getMesh = function () {
  30305. return this._mesh;
  30306. };
  30307. /**
  30308. * Returns the rendering mesh of the submesh.
  30309. */
  30310. SubMesh.prototype.getRenderingMesh = function () {
  30311. return this._renderingMesh;
  30312. };
  30313. /**
  30314. * Returns the submesh material.
  30315. */
  30316. SubMesh.prototype.getMaterial = function () {
  30317. var rootMaterial = this._renderingMesh.material;
  30318. if (rootMaterial === null || rootMaterial === undefined) {
  30319. return this._mesh.getScene().defaultMaterial;
  30320. }
  30321. else if (rootMaterial.getSubMaterial) {
  30322. var multiMaterial = rootMaterial;
  30323. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30324. if (this._currentMaterial !== effectiveMaterial) {
  30325. this._currentMaterial = effectiveMaterial;
  30326. this._materialDefines = null;
  30327. }
  30328. return effectiveMaterial;
  30329. }
  30330. return rootMaterial;
  30331. };
  30332. // Methods
  30333. /**
  30334. * Sets a new updated BoundingInfo object to the submesh.
  30335. * Returns the SubMesh.
  30336. */
  30337. SubMesh.prototype.refreshBoundingInfo = function () {
  30338. this._lastColliderWorldVertices = null;
  30339. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30340. return this;
  30341. }
  30342. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30343. if (!data) {
  30344. this._boundingInfo = this._mesh.getBoundingInfo();
  30345. return this;
  30346. }
  30347. var indices = this._renderingMesh.getIndices();
  30348. var extend;
  30349. //is this the only submesh?
  30350. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30351. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30352. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30353. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30354. }
  30355. else {
  30356. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30357. }
  30358. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30359. return this;
  30360. };
  30361. SubMesh.prototype._checkCollision = function (collider) {
  30362. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30363. return boundingInfo._checkCollision(collider);
  30364. };
  30365. /**
  30366. * Updates the submesh BoundingInfo.
  30367. * Returns the Submesh.
  30368. */
  30369. SubMesh.prototype.updateBoundingInfo = function (world) {
  30370. var boundingInfo = this.getBoundingInfo();
  30371. if (!boundingInfo) {
  30372. this.refreshBoundingInfo();
  30373. boundingInfo = this.getBoundingInfo();
  30374. }
  30375. boundingInfo.update(world);
  30376. return this;
  30377. };
  30378. /**
  30379. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30380. * Boolean returned.
  30381. */
  30382. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30383. var boundingInfo = this.getBoundingInfo();
  30384. if (!boundingInfo) {
  30385. return false;
  30386. }
  30387. return boundingInfo.isInFrustum(frustumPlanes);
  30388. };
  30389. /**
  30390. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30391. * Boolean returned.
  30392. */
  30393. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30394. var boundingInfo = this.getBoundingInfo();
  30395. if (!boundingInfo) {
  30396. return false;
  30397. }
  30398. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30399. };
  30400. /**
  30401. * Renders the submesh.
  30402. * Returns it.
  30403. */
  30404. SubMesh.prototype.render = function (enableAlphaMode) {
  30405. this._renderingMesh.render(this, enableAlphaMode);
  30406. return this;
  30407. };
  30408. /**
  30409. * Returns a new Index Buffer.
  30410. * Type returned : WebGLBuffer.
  30411. */
  30412. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30413. if (!this._linesIndexBuffer) {
  30414. var linesIndices = [];
  30415. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30416. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30417. }
  30418. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30419. this.linesIndexCount = linesIndices.length;
  30420. }
  30421. return this._linesIndexBuffer;
  30422. };
  30423. /**
  30424. * True is the passed Ray intersects the submesh bounding box.
  30425. * Boolean returned.
  30426. */
  30427. SubMesh.prototype.canIntersects = function (ray) {
  30428. var boundingInfo = this.getBoundingInfo();
  30429. if (!boundingInfo) {
  30430. return false;
  30431. }
  30432. return ray.intersectsBox(boundingInfo.boundingBox);
  30433. };
  30434. /**
  30435. * Returns an object IntersectionInfo.
  30436. */
  30437. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30438. var intersectInfo = null;
  30439. // LineMesh first as it's also a Mesh...
  30440. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30441. var lineMesh = this._mesh;
  30442. // Line test
  30443. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30444. var p0 = positions[indices[index]];
  30445. var p1 = positions[indices[index + 1]];
  30446. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30447. if (length < 0) {
  30448. continue;
  30449. }
  30450. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30451. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30452. if (fastCheck) {
  30453. break;
  30454. }
  30455. }
  30456. }
  30457. }
  30458. else {
  30459. // Triangles test
  30460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30461. var p0 = positions[indices[index]];
  30462. var p1 = positions[indices[index + 1]];
  30463. var p2 = positions[indices[index + 2]];
  30464. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30465. if (currentIntersectInfo) {
  30466. if (currentIntersectInfo.distance < 0) {
  30467. continue;
  30468. }
  30469. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30470. intersectInfo = currentIntersectInfo;
  30471. intersectInfo.faceId = index / 3;
  30472. if (fastCheck) {
  30473. break;
  30474. }
  30475. }
  30476. }
  30477. }
  30478. }
  30479. return intersectInfo;
  30480. };
  30481. SubMesh.prototype._rebuild = function () {
  30482. if (this._linesIndexBuffer) {
  30483. this._linesIndexBuffer = null;
  30484. }
  30485. };
  30486. // Clone
  30487. /**
  30488. * Creates a new Submesh from the passed Mesh.
  30489. */
  30490. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30491. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30492. if (!this.IsGlobal) {
  30493. var boundingInfo = this.getBoundingInfo();
  30494. if (!boundingInfo) {
  30495. return result;
  30496. }
  30497. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30498. }
  30499. return result;
  30500. };
  30501. // Dispose
  30502. /**
  30503. * Disposes the Submesh.
  30504. * Returns nothing.
  30505. */
  30506. SubMesh.prototype.dispose = function () {
  30507. if (this._linesIndexBuffer) {
  30508. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30509. this._linesIndexBuffer = null;
  30510. }
  30511. // Remove from mesh
  30512. var index = this._mesh.subMeshes.indexOf(this);
  30513. this._mesh.subMeshes.splice(index, 1);
  30514. };
  30515. // Statics
  30516. /**
  30517. * Creates a new Submesh from the passed parameters :
  30518. * - materialIndex (integer) : the index of the main mesh material.
  30519. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30520. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30521. * - mesh (Mesh) : the main mesh to create the submesh from.
  30522. * - renderingMesh (optional Mesh) : rendering mesh.
  30523. */
  30524. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30525. var minVertexIndex = Number.MAX_VALUE;
  30526. var maxVertexIndex = -Number.MAX_VALUE;
  30527. renderingMesh = (renderingMesh || mesh);
  30528. var indices = renderingMesh.getIndices();
  30529. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30530. var vertexIndex = indices[index];
  30531. if (vertexIndex < minVertexIndex)
  30532. minVertexIndex = vertexIndex;
  30533. if (vertexIndex > maxVertexIndex)
  30534. maxVertexIndex = vertexIndex;
  30535. }
  30536. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30537. };
  30538. return SubMesh;
  30539. }(BaseSubMesh));
  30540. BABYLON.SubMesh = SubMesh;
  30541. })(BABYLON || (BABYLON = {}));
  30542. //# sourceMappingURL=babylon.subMesh.js.map
  30543. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30544. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30545. s = arguments[i];
  30546. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30547. t[p] = s[p];
  30548. }
  30549. return t;
  30550. };
  30551. var BABYLON;
  30552. (function (BABYLON) {
  30553. /**
  30554. * Manages the defines for the Material.
  30555. */
  30556. var MaterialDefines = /** @class */ (function () {
  30557. function MaterialDefines() {
  30558. this._isDirty = true;
  30559. this._areLightsDirty = true;
  30560. this._areAttributesDirty = true;
  30561. this._areTexturesDirty = true;
  30562. this._areFresnelDirty = true;
  30563. this._areMiscDirty = true;
  30564. this._areImageProcessingDirty = true;
  30565. this._normals = false;
  30566. this._uvs = false;
  30567. this._needNormals = false;
  30568. this._needUVs = false;
  30569. }
  30570. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30571. /**
  30572. * Specifies if the material needs to be re-calculated.
  30573. */
  30574. get: function () {
  30575. return this._isDirty;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. /**
  30581. * Marks the material to indicate that it has been re-calculated.
  30582. */
  30583. MaterialDefines.prototype.markAsProcessed = function () {
  30584. this._isDirty = false;
  30585. this._areAttributesDirty = false;
  30586. this._areTexturesDirty = false;
  30587. this._areFresnelDirty = false;
  30588. this._areLightsDirty = false;
  30589. this._areMiscDirty = false;
  30590. this._areImageProcessingDirty = false;
  30591. };
  30592. /**
  30593. * Marks the material to indicate that it needs to be re-calculated.
  30594. */
  30595. MaterialDefines.prototype.markAsUnprocessed = function () {
  30596. this._isDirty = true;
  30597. };
  30598. /**
  30599. * Marks the material to indicate all of its defines need to be re-calculated.
  30600. */
  30601. MaterialDefines.prototype.markAllAsDirty = function () {
  30602. this._areTexturesDirty = true;
  30603. this._areAttributesDirty = true;
  30604. this._areLightsDirty = true;
  30605. this._areFresnelDirty = true;
  30606. this._areMiscDirty = true;
  30607. this._areImageProcessingDirty = true;
  30608. this._isDirty = true;
  30609. };
  30610. /**
  30611. * Marks the material to indicate that image processing needs to be re-calculated.
  30612. */
  30613. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30614. this._areImageProcessingDirty = true;
  30615. this._isDirty = true;
  30616. };
  30617. /**
  30618. * Marks the material to indicate the lights need to be re-calculated.
  30619. */
  30620. MaterialDefines.prototype.markAsLightDirty = function () {
  30621. this._areLightsDirty = true;
  30622. this._isDirty = true;
  30623. };
  30624. /**
  30625. * Marks the attribute state as changed.
  30626. */
  30627. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30628. this._areAttributesDirty = true;
  30629. this._isDirty = true;
  30630. };
  30631. /**
  30632. * Marks the texture state as changed.
  30633. */
  30634. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30635. this._areTexturesDirty = true;
  30636. this._isDirty = true;
  30637. };
  30638. /**
  30639. * Marks the fresnel state as changed.
  30640. */
  30641. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30642. this._areFresnelDirty = true;
  30643. this._isDirty = true;
  30644. };
  30645. /**
  30646. * Marks the misc state as changed.
  30647. */
  30648. MaterialDefines.prototype.markAsMiscDirty = function () {
  30649. this._areMiscDirty = true;
  30650. this._isDirty = true;
  30651. };
  30652. /**
  30653. * Rebuilds the material defines.
  30654. */
  30655. MaterialDefines.prototype.rebuild = function () {
  30656. if (this._keys) {
  30657. delete this._keys;
  30658. }
  30659. this._keys = [];
  30660. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30661. var key = _a[_i];
  30662. if (key[0] === "_") {
  30663. continue;
  30664. }
  30665. this._keys.push(key);
  30666. }
  30667. };
  30668. /**
  30669. * Specifies if two material defines are equal.
  30670. * @param other - A material define instance to compare to.
  30671. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30672. */
  30673. MaterialDefines.prototype.isEqual = function (other) {
  30674. if (this._keys.length !== other._keys.length) {
  30675. return false;
  30676. }
  30677. for (var index = 0; index < this._keys.length; index++) {
  30678. var prop = this._keys[index];
  30679. if (this[prop] !== other[prop]) {
  30680. return false;
  30681. }
  30682. }
  30683. return true;
  30684. };
  30685. /**
  30686. * Clones this instance's defines to another instance.
  30687. * @param other - material defines to clone values to.
  30688. */
  30689. MaterialDefines.prototype.cloneTo = function (other) {
  30690. if (this._keys.length !== other._keys.length) {
  30691. other._keys = this._keys.slice(0);
  30692. }
  30693. for (var index = 0; index < this._keys.length; index++) {
  30694. var prop = this._keys[index];
  30695. other[prop] = this[prop];
  30696. }
  30697. };
  30698. /**
  30699. * Resets the material define values.
  30700. */
  30701. MaterialDefines.prototype.reset = function () {
  30702. for (var index = 0; index < this._keys.length; index++) {
  30703. var prop = this._keys[index];
  30704. if (typeof (this[prop]) === "number") {
  30705. this[prop] = 0;
  30706. }
  30707. else {
  30708. this[prop] = false;
  30709. }
  30710. }
  30711. };
  30712. /**
  30713. * Converts the material define values to a string.
  30714. * @returns - String of material define information.
  30715. */
  30716. MaterialDefines.prototype.toString = function () {
  30717. var result = "";
  30718. for (var index = 0; index < this._keys.length; index++) {
  30719. var prop = this._keys[index];
  30720. var value = this[prop];
  30721. if (typeof (value) === "number") {
  30722. result += "#define " + prop + " " + this[prop] + "\n";
  30723. }
  30724. else if (value) {
  30725. result += "#define " + prop + "\n";
  30726. }
  30727. }
  30728. return result;
  30729. };
  30730. return MaterialDefines;
  30731. }());
  30732. BABYLON.MaterialDefines = MaterialDefines;
  30733. /**
  30734. * This offers the main features of a material in BJS.
  30735. */
  30736. var Material = /** @class */ (function () {
  30737. /**
  30738. * Creates a material instance.
  30739. * @param name - The name of the material.
  30740. * @param scene - The BJS scene to reference.
  30741. * @param doNotAdd - Specifies if the material should be added to the scene.
  30742. */
  30743. function Material(name, scene, doNotAdd) {
  30744. /**
  30745. * Specifies if the ready state should be checked on each call.
  30746. */
  30747. this.checkReadyOnEveryCall = false;
  30748. /**
  30749. * Specifies if the ready state should be checked once.
  30750. */
  30751. this.checkReadyOnlyOnce = false;
  30752. /**
  30753. * The state of the material.
  30754. */
  30755. this.state = "";
  30756. /**
  30757. * The alpha value of the material.
  30758. */
  30759. this._alpha = 1.0;
  30760. /**
  30761. * Specifies if back face culling is enabled.
  30762. */
  30763. this._backFaceCulling = true;
  30764. /**
  30765. * Specifies if the material should be serialized.
  30766. */
  30767. this.doNotSerialize = false;
  30768. /**
  30769. * Specifies if the effect should be stored on sub meshes.
  30770. */
  30771. this.storeEffectOnSubMeshes = false;
  30772. /**
  30773. * An event triggered when the material is disposed.
  30774. * @type {BABYLON.Observable}
  30775. */
  30776. this.onDisposeObservable = new BABYLON.Observable();
  30777. /**
  30778. * An event triggered when the material is bound.
  30779. * @type {BABYLON.Observable}
  30780. */
  30781. this.onBindObservable = new BABYLON.Observable();
  30782. /**
  30783. * An event triggered when the material is unbound.
  30784. * @type {BABYLON.Observable}
  30785. */
  30786. this.onUnBindObservable = new BABYLON.Observable();
  30787. /**
  30788. * Stores the value of the alpha mode.
  30789. */
  30790. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30791. /**
  30792. * Stores the state of the need depth pre-pass value.
  30793. */
  30794. this._needDepthPrePass = false;
  30795. /**
  30796. * Specifies if depth writing should be disabled.
  30797. */
  30798. this.disableDepthWrite = false;
  30799. /**
  30800. * Specifies if depth writing should be forced.
  30801. */
  30802. this.forceDepthWrite = false;
  30803. /**
  30804. * Specifies if there should be a separate pass for culling.
  30805. */
  30806. this.separateCullingPass = false;
  30807. /**
  30808. * Stores the state specifing if fog should be enabled.
  30809. */
  30810. this._fogEnabled = true;
  30811. /**
  30812. * Stores the size of points.
  30813. */
  30814. this.pointSize = 1.0;
  30815. /**
  30816. * Stores the z offset value.
  30817. */
  30818. this.zOffset = 0;
  30819. /**
  30820. * Specifies if the material was previously ready.
  30821. */
  30822. this._wasPreviouslyReady = false;
  30823. /**
  30824. * Stores the fill mode state.
  30825. */
  30826. this._fillMode = Material.TriangleFillMode;
  30827. this.name = name;
  30828. this.id = name || BABYLON.Tools.RandomId();
  30829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30830. if (this._scene.useRightHandedSystem) {
  30831. this.sideOrientation = Material.ClockWiseSideOrientation;
  30832. }
  30833. else {
  30834. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30835. }
  30836. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30837. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30838. if (!doNotAdd) {
  30839. this._scene.materials.push(this);
  30840. }
  30841. }
  30842. Object.defineProperty(Material, "TriangleFillMode", {
  30843. /**
  30844. * Returns the triangle fill mode.
  30845. */
  30846. get: function () {
  30847. return Material._TriangleFillMode;
  30848. },
  30849. enumerable: true,
  30850. configurable: true
  30851. });
  30852. Object.defineProperty(Material, "WireFrameFillMode", {
  30853. /**
  30854. * Returns the wireframe mode.
  30855. */
  30856. get: function () {
  30857. return Material._WireFrameFillMode;
  30858. },
  30859. enumerable: true,
  30860. configurable: true
  30861. });
  30862. Object.defineProperty(Material, "PointFillMode", {
  30863. /**
  30864. * Returns the point fill mode.
  30865. */
  30866. get: function () {
  30867. return Material._PointFillMode;
  30868. },
  30869. enumerable: true,
  30870. configurable: true
  30871. });
  30872. Object.defineProperty(Material, "PointListDrawMode", {
  30873. /**
  30874. * Returns the point list draw mode.
  30875. */
  30876. get: function () {
  30877. return Material._PointListDrawMode;
  30878. },
  30879. enumerable: true,
  30880. configurable: true
  30881. });
  30882. Object.defineProperty(Material, "LineListDrawMode", {
  30883. /**
  30884. * Returns the line list draw mode.
  30885. */
  30886. get: function () {
  30887. return Material._LineListDrawMode;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. Object.defineProperty(Material, "LineLoopDrawMode", {
  30893. /**
  30894. * Returns the line loop draw mode.
  30895. */
  30896. get: function () {
  30897. return Material._LineLoopDrawMode;
  30898. },
  30899. enumerable: true,
  30900. configurable: true
  30901. });
  30902. Object.defineProperty(Material, "LineStripDrawMode", {
  30903. /**
  30904. * Returns the line strip draw mode.
  30905. */
  30906. get: function () {
  30907. return Material._LineStripDrawMode;
  30908. },
  30909. enumerable: true,
  30910. configurable: true
  30911. });
  30912. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30913. /**
  30914. * Returns the triangle strip draw mode.
  30915. */
  30916. get: function () {
  30917. return Material._TriangleStripDrawMode;
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30923. /**
  30924. * Returns the triangle fan draw mode.
  30925. */
  30926. get: function () {
  30927. return Material._TriangleFanDrawMode;
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30933. /**
  30934. * Returns the clock-wise side orientation.
  30935. */
  30936. get: function () {
  30937. return Material._ClockWiseSideOrientation;
  30938. },
  30939. enumerable: true,
  30940. configurable: true
  30941. });
  30942. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30943. /**
  30944. * Returns the counter clock-wise side orientation.
  30945. */
  30946. get: function () {
  30947. return Material._CounterClockWiseSideOrientation;
  30948. },
  30949. enumerable: true,
  30950. configurable: true
  30951. });
  30952. Object.defineProperty(Material, "TextureDirtyFlag", {
  30953. /**
  30954. * Returns the dirty texture flag value.
  30955. */
  30956. get: function () {
  30957. return Material._TextureDirtyFlag;
  30958. },
  30959. enumerable: true,
  30960. configurable: true
  30961. });
  30962. Object.defineProperty(Material, "LightDirtyFlag", {
  30963. /**
  30964. * Returns the dirty light flag value.
  30965. */
  30966. get: function () {
  30967. return Material._LightDirtyFlag;
  30968. },
  30969. enumerable: true,
  30970. configurable: true
  30971. });
  30972. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30973. /**
  30974. * Returns the dirty fresnel flag value.
  30975. */
  30976. get: function () {
  30977. return Material._FresnelDirtyFlag;
  30978. },
  30979. enumerable: true,
  30980. configurable: true
  30981. });
  30982. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30983. /**
  30984. * Returns the dirty attributes flag value.
  30985. */
  30986. get: function () {
  30987. return Material._AttributesDirtyFlag;
  30988. },
  30989. enumerable: true,
  30990. configurable: true
  30991. });
  30992. Object.defineProperty(Material, "MiscDirtyFlag", {
  30993. /**
  30994. * Returns the dirty misc flag value.
  30995. */
  30996. get: function () {
  30997. return Material._MiscDirtyFlag;
  30998. },
  30999. enumerable: true,
  31000. configurable: true
  31001. });
  31002. Object.defineProperty(Material.prototype, "alpha", {
  31003. /**
  31004. * Gets the alpha value of the material.
  31005. */
  31006. get: function () {
  31007. return this._alpha;
  31008. },
  31009. /**
  31010. * Sets the alpha value of the material.
  31011. */
  31012. set: function (value) {
  31013. if (this._alpha === value) {
  31014. return;
  31015. }
  31016. this._alpha = value;
  31017. this.markAsDirty(Material.MiscDirtyFlag);
  31018. },
  31019. enumerable: true,
  31020. configurable: true
  31021. });
  31022. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31023. /**
  31024. * Gets the back-face culling state.
  31025. */
  31026. get: function () {
  31027. return this._backFaceCulling;
  31028. },
  31029. /**
  31030. * Sets the back-face culling state.
  31031. */
  31032. set: function (value) {
  31033. if (this._backFaceCulling === value) {
  31034. return;
  31035. }
  31036. this._backFaceCulling = value;
  31037. this.markAsDirty(Material.TextureDirtyFlag);
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(Material.prototype, "onDispose", {
  31043. /**
  31044. * Called during a dispose event.
  31045. */
  31046. set: function (callback) {
  31047. if (this._onDisposeObserver) {
  31048. this.onDisposeObservable.remove(this._onDisposeObserver);
  31049. }
  31050. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Material.prototype, "onBind", {
  31056. /**
  31057. * Called during a bind event.
  31058. */
  31059. set: function (callback) {
  31060. if (this._onBindObserver) {
  31061. this.onBindObservable.remove(this._onBindObserver);
  31062. }
  31063. this._onBindObserver = this.onBindObservable.add(callback);
  31064. },
  31065. enumerable: true,
  31066. configurable: true
  31067. });
  31068. Object.defineProperty(Material.prototype, "alphaMode", {
  31069. /**
  31070. * Gets the value of the alpha mode.
  31071. */
  31072. get: function () {
  31073. return this._alphaMode;
  31074. },
  31075. /**
  31076. * Sets the value of the alpha mode.
  31077. */
  31078. set: function (value) {
  31079. if (this._alphaMode === value) {
  31080. return;
  31081. }
  31082. this._alphaMode = value;
  31083. this.markAsDirty(Material.TextureDirtyFlag);
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31089. /**
  31090. * Gets the depth pre-pass value.
  31091. */
  31092. get: function () {
  31093. return this._needDepthPrePass;
  31094. },
  31095. /**
  31096. * Sets the need depth pre-pass value.
  31097. */
  31098. set: function (value) {
  31099. if (this._needDepthPrePass === value) {
  31100. return;
  31101. }
  31102. this._needDepthPrePass = value;
  31103. if (this._needDepthPrePass) {
  31104. this.checkReadyOnEveryCall = true;
  31105. }
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Material.prototype, "fogEnabled", {
  31111. /**
  31112. * Gets the value of the fog enabled state.
  31113. */
  31114. get: function () {
  31115. return this._fogEnabled;
  31116. },
  31117. /**
  31118. * Sets the state for enabling fog.
  31119. */
  31120. set: function (value) {
  31121. if (this._fogEnabled === value) {
  31122. return;
  31123. }
  31124. this._fogEnabled = value;
  31125. this.markAsDirty(Material.MiscDirtyFlag);
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(Material.prototype, "wireframe", {
  31131. /**
  31132. * Gets a value specifying if wireframe mode is enabled.
  31133. */
  31134. get: function () {
  31135. return this._fillMode === Material.WireFrameFillMode;
  31136. },
  31137. /**
  31138. * Sets the state of wireframe mode.
  31139. */
  31140. set: function (value) {
  31141. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. Object.defineProperty(Material.prototype, "pointsCloud", {
  31147. /**
  31148. * Gets the value specifying if point clouds are enabled.
  31149. */
  31150. get: function () {
  31151. return this._fillMode === Material.PointFillMode;
  31152. },
  31153. /**
  31154. * Sets the state of point cloud mode.
  31155. */
  31156. set: function (value) {
  31157. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31158. },
  31159. enumerable: true,
  31160. configurable: true
  31161. });
  31162. Object.defineProperty(Material.prototype, "fillMode", {
  31163. /**
  31164. * Gets the material fill mode.
  31165. */
  31166. get: function () {
  31167. return this._fillMode;
  31168. },
  31169. /**
  31170. * Sets the material fill mode.
  31171. */
  31172. set: function (value) {
  31173. if (this._fillMode === value) {
  31174. return;
  31175. }
  31176. this._fillMode = value;
  31177. this.markAsDirty(Material.MiscDirtyFlag);
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. /**
  31183. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31184. * subclasses should override adding information pertainent to themselves.
  31185. * @returns - String with material information.
  31186. */
  31187. Material.prototype.toString = function (fullDetails) {
  31188. var ret = "Name: " + this.name;
  31189. if (fullDetails) {
  31190. }
  31191. return ret;
  31192. };
  31193. /**
  31194. * Gets the class name of the material.
  31195. * @returns - String with the class name of the material.
  31196. */
  31197. Material.prototype.getClassName = function () {
  31198. return "Material";
  31199. };
  31200. Object.defineProperty(Material.prototype, "isFrozen", {
  31201. /**
  31202. * Specifies if updates for the material been locked.
  31203. */
  31204. get: function () {
  31205. return this.checkReadyOnlyOnce;
  31206. },
  31207. enumerable: true,
  31208. configurable: true
  31209. });
  31210. /**
  31211. * Locks updates for the material.
  31212. */
  31213. Material.prototype.freeze = function () {
  31214. this.checkReadyOnlyOnce = true;
  31215. };
  31216. /**
  31217. * Unlocks updates for the material.
  31218. */
  31219. Material.prototype.unfreeze = function () {
  31220. this.checkReadyOnlyOnce = false;
  31221. };
  31222. /**
  31223. * Specifies if the material is ready to be used.
  31224. * @param mesh - BJS mesh.
  31225. * @param useInstances - Specifies if instances should be used.
  31226. * @returns - Boolean indicating if the material is ready to be used.
  31227. */
  31228. Material.prototype.isReady = function (mesh, useInstances) {
  31229. return true;
  31230. };
  31231. /**
  31232. * Specifies that the submesh is ready to be used.
  31233. * @param mesh - BJS mesh.
  31234. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31235. * @param useInstances - Specifies that instances should be used.
  31236. * @returns - boolean indicating that the submesh is ready or not.
  31237. */
  31238. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31239. return false;
  31240. };
  31241. /**
  31242. * Returns the material effect.
  31243. * @returns - Nullable material effect.
  31244. */
  31245. Material.prototype.getEffect = function () {
  31246. return this._effect;
  31247. };
  31248. /**
  31249. * Returns the BJS scene.
  31250. * @returns - BJS Scene.
  31251. */
  31252. Material.prototype.getScene = function () {
  31253. return this._scene;
  31254. };
  31255. /**
  31256. * Specifies if the material will require alpha blending
  31257. * @returns - Boolean specifying if alpha blending is needed.
  31258. */
  31259. Material.prototype.needAlphaBlending = function () {
  31260. return (this.alpha < 1.0);
  31261. };
  31262. /**
  31263. * Specifies if the mesh will require alpha blending.
  31264. * @param mesh - BJS mesh.
  31265. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31266. */
  31267. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31268. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31269. };
  31270. /**
  31271. * Specifies if this material should be rendered in alpha test mode.
  31272. * @returns - Boolean specifying if an alpha test is needed.
  31273. */
  31274. Material.prototype.needAlphaTesting = function () {
  31275. return false;
  31276. };
  31277. /**
  31278. * Gets the texture used for the alpha test.
  31279. * @returns - Nullable alpha test texture.
  31280. */
  31281. Material.prototype.getAlphaTestTexture = function () {
  31282. return null;
  31283. };
  31284. /**
  31285. * Marks the material to indicate that it needs to be re-calculated.
  31286. */
  31287. Material.prototype.markDirty = function () {
  31288. this._wasPreviouslyReady = false;
  31289. };
  31290. Material.prototype._preBind = function (effect, overrideOrientation) {
  31291. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31292. var engine = this._scene.getEngine();
  31293. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31294. var reverse = orientation === Material.ClockWiseSideOrientation;
  31295. engine.enableEffect(effect ? effect : this._effect);
  31296. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31297. return reverse;
  31298. };
  31299. /**
  31300. * Binds the material to the mesh.
  31301. * @param world - World transformation matrix.
  31302. * @param mesh - Mesh to bind the material to.
  31303. */
  31304. Material.prototype.bind = function (world, mesh) {
  31305. };
  31306. /**
  31307. * Binds the submesh to the material.
  31308. * @param world - World transformation matrix.
  31309. * @param mesh - Mesh containing the submesh.
  31310. * @param subMesh - Submesh to bind the material to.
  31311. */
  31312. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31313. };
  31314. /**
  31315. * Binds the world matrix to the material.
  31316. * @param world - World transformation matrix.
  31317. */
  31318. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31319. };
  31320. /**
  31321. * Binds the scene's uniform buffer to the effect.
  31322. * @param effect - Effect to bind to the scene uniform buffer.
  31323. * @param sceneUbo - Scene uniform buffer.
  31324. */
  31325. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31326. sceneUbo.bindToEffect(effect, "Scene");
  31327. };
  31328. /**
  31329. * Binds the view matrix to the effect.
  31330. * @param effect - Effect to bind the view matrix to.
  31331. */
  31332. Material.prototype.bindView = function (effect) {
  31333. if (!this._useUBO) {
  31334. effect.setMatrix("view", this.getScene().getViewMatrix());
  31335. }
  31336. else {
  31337. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31338. }
  31339. };
  31340. /**
  31341. * Binds the view projection matrix to the effect.
  31342. * @param effect - Effect to bind the view projection matrix to.
  31343. */
  31344. Material.prototype.bindViewProjection = function (effect) {
  31345. if (!this._useUBO) {
  31346. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31347. }
  31348. else {
  31349. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31350. }
  31351. };
  31352. /**
  31353. * Specifies if material alpha testing should be turned on for the mesh.
  31354. * @param mesh - BJS mesh.
  31355. */
  31356. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31357. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31358. };
  31359. /**
  31360. * Processes to execute after binding the material to a mesh.
  31361. * @param mesh - BJS mesh.
  31362. */
  31363. Material.prototype._afterBind = function (mesh) {
  31364. this._scene._cachedMaterial = this;
  31365. if (mesh) {
  31366. this._scene._cachedVisibility = mesh.visibility;
  31367. }
  31368. else {
  31369. this._scene._cachedVisibility = 1;
  31370. }
  31371. if (mesh) {
  31372. this.onBindObservable.notifyObservers(mesh);
  31373. }
  31374. if (this.disableDepthWrite) {
  31375. var engine = this._scene.getEngine();
  31376. this._cachedDepthWriteState = engine.getDepthWrite();
  31377. engine.setDepthWrite(false);
  31378. }
  31379. };
  31380. /**
  31381. * Unbinds the material from the mesh.
  31382. */
  31383. Material.prototype.unbind = function () {
  31384. this.onUnBindObservable.notifyObservers(this);
  31385. if (this.disableDepthWrite) {
  31386. var engine = this._scene.getEngine();
  31387. engine.setDepthWrite(this._cachedDepthWriteState);
  31388. }
  31389. };
  31390. /**
  31391. * Gets the active textures from the material.
  31392. * @returns - Array of textures.
  31393. */
  31394. Material.prototype.getActiveTextures = function () {
  31395. return [];
  31396. };
  31397. /**
  31398. * Specifies if the material uses a texture.
  31399. * @param texture - Texture to check against the material.
  31400. * @returns - Boolean specifying if the material uses the texture.
  31401. */
  31402. Material.prototype.hasTexture = function (texture) {
  31403. return false;
  31404. };
  31405. /**
  31406. * Makes a duplicate of the material, and gives it a new name.
  31407. * @param name - Name to call the duplicated material.
  31408. * @returns - Nullable cloned material
  31409. */
  31410. Material.prototype.clone = function (name) {
  31411. return null;
  31412. };
  31413. /**
  31414. * Gets the meshes bound to the material.
  31415. * @returns - Array of meshes bound to the material.
  31416. */
  31417. Material.prototype.getBindedMeshes = function () {
  31418. var result = new Array();
  31419. for (var index = 0; index < this._scene.meshes.length; index++) {
  31420. var mesh = this._scene.meshes[index];
  31421. if (mesh.material === this) {
  31422. result.push(mesh);
  31423. }
  31424. }
  31425. return result;
  31426. };
  31427. /**
  31428. * Force shader compilation
  31429. * @param mesh - BJS mesh.
  31430. * @param onCompiled - function to execute once the material is compiled.
  31431. * @param options - options to pass to this function.
  31432. */
  31433. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31434. var _this = this;
  31435. var localOptions = __assign({ clipPlane: false }, options);
  31436. var subMesh = new BABYLON.BaseSubMesh();
  31437. var scene = this.getScene();
  31438. var checkReady = function () {
  31439. if (!_this._scene || !_this._scene.getEngine()) {
  31440. return;
  31441. }
  31442. if (subMesh._materialDefines) {
  31443. subMesh._materialDefines._renderId = -1;
  31444. }
  31445. var clipPlaneState = scene.clipPlane;
  31446. if (localOptions.clipPlane) {
  31447. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31448. }
  31449. if (_this.storeEffectOnSubMeshes) {
  31450. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31451. if (onCompiled) {
  31452. onCompiled(_this);
  31453. }
  31454. }
  31455. else {
  31456. setTimeout(checkReady, 16);
  31457. }
  31458. }
  31459. else {
  31460. if (_this.isReady(mesh)) {
  31461. if (onCompiled) {
  31462. onCompiled(_this);
  31463. }
  31464. }
  31465. else {
  31466. setTimeout(checkReady, 16);
  31467. }
  31468. }
  31469. if (localOptions.clipPlane) {
  31470. scene.clipPlane = clipPlaneState;
  31471. }
  31472. };
  31473. checkReady();
  31474. };
  31475. /**
  31476. * Force shader compilation.
  31477. * @param mesh The mesh that will use this material
  31478. * @param options Additional options for compiling the shaders
  31479. * @returns A promise that resolves when the compilation completes
  31480. */
  31481. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31482. var _this = this;
  31483. return new Promise(function (resolve) {
  31484. _this.forceCompilation(mesh, function () {
  31485. resolve();
  31486. }, options);
  31487. });
  31488. };
  31489. /**
  31490. * Marks a define in the material to indicate that it needs to be re-computed.
  31491. * @param flag - Material define flag.
  31492. */
  31493. Material.prototype.markAsDirty = function (flag) {
  31494. if (flag & Material.TextureDirtyFlag) {
  31495. this._markAllSubMeshesAsTexturesDirty();
  31496. }
  31497. if (flag & Material.LightDirtyFlag) {
  31498. this._markAllSubMeshesAsLightsDirty();
  31499. }
  31500. if (flag & Material.FresnelDirtyFlag) {
  31501. this._markAllSubMeshesAsFresnelDirty();
  31502. }
  31503. if (flag & Material.AttributesDirtyFlag) {
  31504. this._markAllSubMeshesAsAttributesDirty();
  31505. }
  31506. if (flag & Material.MiscDirtyFlag) {
  31507. this._markAllSubMeshesAsMiscDirty();
  31508. }
  31509. this.getScene().resetCachedMaterial();
  31510. };
  31511. /**
  31512. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31513. * @param func - function which checks material defines against the submeshes.
  31514. */
  31515. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31516. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31517. var mesh = _a[_i];
  31518. if (!mesh.subMeshes) {
  31519. continue;
  31520. }
  31521. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31522. var subMesh = _c[_b];
  31523. if (subMesh.getMaterial() !== this) {
  31524. continue;
  31525. }
  31526. if (!subMesh._materialDefines) {
  31527. continue;
  31528. }
  31529. func(subMesh._materialDefines);
  31530. }
  31531. }
  31532. };
  31533. /**
  31534. * Indicates that image processing needs to be re-calculated for all submeshes.
  31535. */
  31536. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31537. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31538. };
  31539. /**
  31540. * Indicates that textures need to be re-calculated for all submeshes.
  31541. */
  31542. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31543. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31544. };
  31545. /**
  31546. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31547. */
  31548. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31549. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31550. };
  31551. /**
  31552. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31553. */
  31554. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31555. this._markAllSubMeshesAsDirty(function (defines) {
  31556. defines.markAsFresnelDirty();
  31557. defines.markAsMiscDirty();
  31558. });
  31559. };
  31560. /**
  31561. * Indicates that lights need to be re-calculated for all submeshes.
  31562. */
  31563. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31564. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31565. };
  31566. /**
  31567. * Indicates that attributes need to be re-calculated for all submeshes.
  31568. */
  31569. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31570. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31571. };
  31572. /**
  31573. * Indicates that misc needs to be re-calculated for all submeshes.
  31574. */
  31575. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31576. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31577. };
  31578. /**
  31579. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31580. */
  31581. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31582. this._markAllSubMeshesAsDirty(function (defines) {
  31583. defines.markAsTexturesDirty();
  31584. defines.markAsMiscDirty();
  31585. });
  31586. };
  31587. /**
  31588. * Disposes the material.
  31589. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31590. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31591. */
  31592. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31593. // Animations
  31594. this.getScene().stopAnimation(this);
  31595. // Remove from scene
  31596. var index = this._scene.materials.indexOf(this);
  31597. if (index >= 0) {
  31598. this._scene.materials.splice(index, 1);
  31599. }
  31600. // Remove from meshes
  31601. for (index = 0; index < this._scene.meshes.length; index++) {
  31602. var mesh = this._scene.meshes[index];
  31603. if (mesh.material === this) {
  31604. mesh.material = null;
  31605. if (mesh.geometry) {
  31606. var geometry = (mesh.geometry);
  31607. if (this.storeEffectOnSubMeshes) {
  31608. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31609. var subMesh = _a[_i];
  31610. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31611. if (forceDisposeEffect && subMesh._materialEffect) {
  31612. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31613. }
  31614. }
  31615. }
  31616. else {
  31617. geometry._releaseVertexArrayObject(this._effect);
  31618. }
  31619. }
  31620. }
  31621. }
  31622. this._uniformBuffer.dispose();
  31623. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31624. if (forceDisposeEffect && this._effect) {
  31625. if (!this.storeEffectOnSubMeshes) {
  31626. this._scene.getEngine()._releaseEffect(this._effect);
  31627. }
  31628. this._effect = null;
  31629. }
  31630. // Callback
  31631. this.onDisposeObservable.notifyObservers(this);
  31632. this.onDisposeObservable.clear();
  31633. this.onBindObservable.clear();
  31634. this.onUnBindObservable.clear();
  31635. };
  31636. /**
  31637. * Serializes this material.
  31638. * @returns - serialized material object.
  31639. */
  31640. Material.prototype.serialize = function () {
  31641. return BABYLON.SerializationHelper.Serialize(this);
  31642. };
  31643. /**
  31644. * Creates a MultiMaterial from parse MultiMaterial data.
  31645. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31646. * @param scene - BJS scene.
  31647. * @returns - MultiMaterial.
  31648. */
  31649. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31650. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31651. multiMaterial.id = parsedMultiMaterial.id;
  31652. if (BABYLON.Tags) {
  31653. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31654. }
  31655. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31656. var subMatId = parsedMultiMaterial.materials[matIndex];
  31657. if (subMatId) {
  31658. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31659. }
  31660. else {
  31661. multiMaterial.subMaterials.push(null);
  31662. }
  31663. }
  31664. return multiMaterial;
  31665. };
  31666. /**
  31667. * Creates a material from parsed material data.
  31668. * @param parsedMaterial - Parsed material data.
  31669. * @param scene - BJS scene.
  31670. * @param rootUrl - Root URL containing the material information.
  31671. * @returns - Parsed material.
  31672. */
  31673. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31674. if (!parsedMaterial.customType) {
  31675. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31676. }
  31677. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31678. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31679. if (!BABYLON.LegacyPBRMaterial) {
  31680. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31681. return;
  31682. }
  31683. }
  31684. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31685. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31686. ;
  31687. };
  31688. // Triangle views
  31689. Material._TriangleFillMode = 0;
  31690. Material._WireFrameFillMode = 1;
  31691. Material._PointFillMode = 2;
  31692. // Draw modes
  31693. Material._PointListDrawMode = 3;
  31694. Material._LineListDrawMode = 4;
  31695. Material._LineLoopDrawMode = 5;
  31696. Material._LineStripDrawMode = 6;
  31697. Material._TriangleStripDrawMode = 7;
  31698. Material._TriangleFanDrawMode = 8;
  31699. /**
  31700. * Stores the clock-wise side orientation.
  31701. */
  31702. Material._ClockWiseSideOrientation = 0;
  31703. /**
  31704. * Stores the counter clock-wise side orientation.
  31705. */
  31706. Material._CounterClockWiseSideOrientation = 1;
  31707. /**
  31708. * The dirty texture flag value.
  31709. */
  31710. Material._TextureDirtyFlag = 1;
  31711. /**
  31712. * The dirty light flag value.
  31713. */
  31714. Material._LightDirtyFlag = 2;
  31715. /**
  31716. * The dirty fresnel flag value.
  31717. */
  31718. Material._FresnelDirtyFlag = 4;
  31719. /**
  31720. * The dirty attribute flag value.
  31721. */
  31722. Material._AttributesDirtyFlag = 8;
  31723. /**
  31724. * The dirty misc flag value.
  31725. */
  31726. Material._MiscDirtyFlag = 16;
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], Material.prototype, "id", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], Material.prototype, "name", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31736. __decorate([
  31737. BABYLON.serialize()
  31738. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31739. __decorate([
  31740. BABYLON.serialize()
  31741. ], Material.prototype, "state", void 0);
  31742. __decorate([
  31743. BABYLON.serialize("alpha")
  31744. ], Material.prototype, "_alpha", void 0);
  31745. __decorate([
  31746. BABYLON.serialize("backFaceCulling")
  31747. ], Material.prototype, "_backFaceCulling", void 0);
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], Material.prototype, "sideOrientation", void 0);
  31751. __decorate([
  31752. BABYLON.serialize("alphaMode")
  31753. ], Material.prototype, "_alphaMode", void 0);
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], Material.prototype, "_needDepthPrePass", void 0);
  31757. __decorate([
  31758. BABYLON.serialize()
  31759. ], Material.prototype, "disableDepthWrite", void 0);
  31760. __decorate([
  31761. BABYLON.serialize()
  31762. ], Material.prototype, "forceDepthWrite", void 0);
  31763. __decorate([
  31764. BABYLON.serialize()
  31765. ], Material.prototype, "separateCullingPass", void 0);
  31766. __decorate([
  31767. BABYLON.serialize("fogEnabled")
  31768. ], Material.prototype, "_fogEnabled", void 0);
  31769. __decorate([
  31770. BABYLON.serialize()
  31771. ], Material.prototype, "pointSize", void 0);
  31772. __decorate([
  31773. BABYLON.serialize()
  31774. ], Material.prototype, "zOffset", void 0);
  31775. __decorate([
  31776. BABYLON.serialize()
  31777. ], Material.prototype, "wireframe", null);
  31778. __decorate([
  31779. BABYLON.serialize()
  31780. ], Material.prototype, "pointsCloud", null);
  31781. __decorate([
  31782. BABYLON.serialize()
  31783. ], Material.prototype, "fillMode", null);
  31784. return Material;
  31785. }());
  31786. BABYLON.Material = Material;
  31787. })(BABYLON || (BABYLON = {}));
  31788. //# sourceMappingURL=babylon.material.js.map
  31789. var BABYLON;
  31790. (function (BABYLON) {
  31791. var UniformBuffer = /** @class */ (function () {
  31792. /**
  31793. * Uniform buffer objects.
  31794. *
  31795. * Handles blocks of uniform on the GPU.
  31796. *
  31797. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31798. *
  31799. * For more information, please refer to :
  31800. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31801. */
  31802. function UniformBuffer(engine, data, dynamic) {
  31803. this._engine = engine;
  31804. this._noUBO = !engine.supportsUniformBuffers;
  31805. this._dynamic = dynamic;
  31806. this._data = data || [];
  31807. this._uniformLocations = {};
  31808. this._uniformSizes = {};
  31809. this._uniformLocationPointer = 0;
  31810. this._needSync = false;
  31811. if (this._noUBO) {
  31812. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31813. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31814. this.updateFloat = this._updateFloatForEffect;
  31815. this.updateFloat2 = this._updateFloat2ForEffect;
  31816. this.updateFloat3 = this._updateFloat3ForEffect;
  31817. this.updateFloat4 = this._updateFloat4ForEffect;
  31818. this.updateMatrix = this._updateMatrixForEffect;
  31819. this.updateVector3 = this._updateVector3ForEffect;
  31820. this.updateVector4 = this._updateVector4ForEffect;
  31821. this.updateColor3 = this._updateColor3ForEffect;
  31822. this.updateColor4 = this._updateColor4ForEffect;
  31823. }
  31824. else {
  31825. this._engine._uniformBuffers.push(this);
  31826. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31827. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31828. this.updateFloat = this._updateFloatForUniform;
  31829. this.updateFloat2 = this._updateFloat2ForUniform;
  31830. this.updateFloat3 = this._updateFloat3ForUniform;
  31831. this.updateFloat4 = this._updateFloat4ForUniform;
  31832. this.updateMatrix = this._updateMatrixForUniform;
  31833. this.updateVector3 = this._updateVector3ForUniform;
  31834. this.updateVector4 = this._updateVector4ForUniform;
  31835. this.updateColor3 = this._updateColor3ForUniform;
  31836. this.updateColor4 = this._updateColor4ForUniform;
  31837. }
  31838. }
  31839. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31840. // Properties
  31841. /**
  31842. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31843. * or just falling back on setUniformXXX calls.
  31844. */
  31845. get: function () {
  31846. return !this._noUBO;
  31847. },
  31848. enumerable: true,
  31849. configurable: true
  31850. });
  31851. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31852. /**
  31853. * Indicates if the WebGL underlying uniform buffer is in sync
  31854. * with the javascript cache data.
  31855. */
  31856. get: function () {
  31857. return !this._needSync;
  31858. },
  31859. enumerable: true,
  31860. configurable: true
  31861. });
  31862. /**
  31863. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31864. * Also, a dynamic UniformBuffer will disable cache verification and always
  31865. * update the underlying WebGL uniform buffer to the GPU.
  31866. */
  31867. UniformBuffer.prototype.isDynamic = function () {
  31868. return this._dynamic !== undefined;
  31869. };
  31870. /**
  31871. * The data cache on JS side.
  31872. */
  31873. UniformBuffer.prototype.getData = function () {
  31874. return this._bufferData;
  31875. };
  31876. /**
  31877. * The underlying WebGL Uniform buffer.
  31878. */
  31879. UniformBuffer.prototype.getBuffer = function () {
  31880. return this._buffer;
  31881. };
  31882. /**
  31883. * std140 layout specifies how to align data within an UBO structure.
  31884. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31885. * for specs.
  31886. */
  31887. UniformBuffer.prototype._fillAlignment = function (size) {
  31888. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31889. // and 4x4 matrices
  31890. // TODO : change if other types are used
  31891. var alignment;
  31892. if (size <= 2) {
  31893. alignment = size;
  31894. }
  31895. else {
  31896. alignment = 4;
  31897. }
  31898. if ((this._uniformLocationPointer % alignment) !== 0) {
  31899. var oldPointer = this._uniformLocationPointer;
  31900. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31901. var diff = this._uniformLocationPointer - oldPointer;
  31902. for (var i = 0; i < diff; i++) {
  31903. this._data.push(0);
  31904. }
  31905. }
  31906. };
  31907. /**
  31908. * Adds an uniform in the buffer.
  31909. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31910. * for the layout to be correct !
  31911. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31912. * @param {number|number[]} size Data size, or data directly.
  31913. */
  31914. UniformBuffer.prototype.addUniform = function (name, size) {
  31915. if (this._noUBO) {
  31916. return;
  31917. }
  31918. if (this._uniformLocations[name] !== undefined) {
  31919. // Already existing uniform
  31920. return;
  31921. }
  31922. // This function must be called in the order of the shader layout !
  31923. // size can be the size of the uniform, or data directly
  31924. var data;
  31925. if (size instanceof Array) {
  31926. data = size;
  31927. size = data.length;
  31928. }
  31929. else {
  31930. size = size;
  31931. data = [];
  31932. // Fill with zeros
  31933. for (var i = 0; i < size; i++) {
  31934. data.push(0);
  31935. }
  31936. }
  31937. this._fillAlignment(size);
  31938. this._uniformSizes[name] = size;
  31939. this._uniformLocations[name] = this._uniformLocationPointer;
  31940. this._uniformLocationPointer += size;
  31941. for (var i = 0; i < size; i++) {
  31942. this._data.push(data[i]);
  31943. }
  31944. this._needSync = true;
  31945. };
  31946. /**
  31947. * Wrapper for addUniform.
  31948. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31949. * @param {Matrix} mat A 4x4 matrix.
  31950. */
  31951. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31952. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31953. };
  31954. /**
  31955. * Wrapper for addUniform.
  31956. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31957. * @param {number} x
  31958. * @param {number} y
  31959. */
  31960. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31961. var temp = [x, y];
  31962. this.addUniform(name, temp);
  31963. };
  31964. /**
  31965. * Wrapper for addUniform.
  31966. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31967. * @param {number} x
  31968. * @param {number} y
  31969. * @param {number} z
  31970. */
  31971. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31972. var temp = [x, y, z];
  31973. this.addUniform(name, temp);
  31974. };
  31975. /**
  31976. * Wrapper for addUniform.
  31977. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31978. * @param {Color3} color
  31979. */
  31980. UniformBuffer.prototype.addColor3 = function (name, color) {
  31981. var temp = new Array();
  31982. color.toArray(temp);
  31983. this.addUniform(name, temp);
  31984. };
  31985. /**
  31986. * Wrapper for addUniform.
  31987. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31988. * @param {Color3} color
  31989. * @param {number} alpha
  31990. */
  31991. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31992. var temp = new Array();
  31993. color.toArray(temp);
  31994. temp.push(alpha);
  31995. this.addUniform(name, temp);
  31996. };
  31997. /**
  31998. * Wrapper for addUniform.
  31999. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32000. * @param {Vector3} vector
  32001. */
  32002. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32003. var temp = new Array();
  32004. vector.toArray(temp);
  32005. this.addUniform(name, temp);
  32006. };
  32007. /**
  32008. * Wrapper for addUniform.
  32009. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32010. */
  32011. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32012. this.addUniform(name, 12);
  32013. };
  32014. /**
  32015. * Wrapper for addUniform.
  32016. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32017. */
  32018. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32019. this.addUniform(name, 8);
  32020. };
  32021. /**
  32022. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32023. */
  32024. UniformBuffer.prototype.create = function () {
  32025. if (this._noUBO) {
  32026. return;
  32027. }
  32028. if (this._buffer) {
  32029. return; // nothing to do
  32030. }
  32031. // See spec, alignment must be filled as a vec4
  32032. this._fillAlignment(4);
  32033. this._bufferData = new Float32Array(this._data);
  32034. this._rebuild();
  32035. this._needSync = true;
  32036. };
  32037. UniformBuffer.prototype._rebuild = function () {
  32038. if (this._noUBO) {
  32039. return;
  32040. }
  32041. if (this._dynamic) {
  32042. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32043. }
  32044. else {
  32045. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32046. }
  32047. };
  32048. /**
  32049. * Updates the WebGL Uniform Buffer on the GPU.
  32050. * If the `dynamic` flag is set to true, no cache comparison is done.
  32051. * Otherwise, the buffer will be updated only if the cache differs.
  32052. */
  32053. UniformBuffer.prototype.update = function () {
  32054. if (!this._buffer) {
  32055. this.create();
  32056. return;
  32057. }
  32058. if (!this._dynamic && !this._needSync) {
  32059. return;
  32060. }
  32061. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32062. this._needSync = false;
  32063. };
  32064. /**
  32065. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32066. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32067. * @param {number[]|Float32Array} data Flattened data
  32068. * @param {number} size Size of the data.
  32069. */
  32070. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32071. var location = this._uniformLocations[uniformName];
  32072. if (location === undefined) {
  32073. if (this._buffer) {
  32074. // Cannot add an uniform if the buffer is already created
  32075. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32076. return;
  32077. }
  32078. this.addUniform(uniformName, size);
  32079. location = this._uniformLocations[uniformName];
  32080. }
  32081. if (!this._buffer) {
  32082. this.create();
  32083. }
  32084. if (!this._dynamic) {
  32085. // Cache for static uniform buffers
  32086. var changed = false;
  32087. for (var i = 0; i < size; i++) {
  32088. if (this._bufferData[location + i] !== data[i]) {
  32089. changed = true;
  32090. this._bufferData[location + i] = data[i];
  32091. }
  32092. }
  32093. this._needSync = this._needSync || changed;
  32094. }
  32095. else {
  32096. // No cache for dynamic
  32097. for (var i = 0; i < size; i++) {
  32098. this._bufferData[location + i] = data[i];
  32099. }
  32100. }
  32101. };
  32102. // Update methods
  32103. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32104. // To match std140, matrix must be realigned
  32105. for (var i = 0; i < 3; i++) {
  32106. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32107. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32108. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32109. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32110. }
  32111. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32112. };
  32113. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32114. this._currentEffect.setMatrix3x3(name, matrix);
  32115. };
  32116. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32117. this._currentEffect.setMatrix2x2(name, matrix);
  32118. };
  32119. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32120. // To match std140, matrix must be realigned
  32121. for (var i = 0; i < 2; i++) {
  32122. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32123. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32124. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32125. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32126. }
  32127. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32128. };
  32129. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32130. this._currentEffect.setFloat(name, x);
  32131. };
  32132. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32133. UniformBuffer._tempBuffer[0] = x;
  32134. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32135. };
  32136. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. this._currentEffect.setFloat2(name + suffix, x, y);
  32139. };
  32140. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32141. if (suffix === void 0) { suffix = ""; }
  32142. UniformBuffer._tempBuffer[0] = x;
  32143. UniformBuffer._tempBuffer[1] = y;
  32144. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32145. };
  32146. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32147. if (suffix === void 0) { suffix = ""; }
  32148. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32149. };
  32150. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32151. if (suffix === void 0) { suffix = ""; }
  32152. UniformBuffer._tempBuffer[0] = x;
  32153. UniformBuffer._tempBuffer[1] = y;
  32154. UniformBuffer._tempBuffer[2] = z;
  32155. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32156. };
  32157. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32158. if (suffix === void 0) { suffix = ""; }
  32159. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32160. };
  32161. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32162. if (suffix === void 0) { suffix = ""; }
  32163. UniformBuffer._tempBuffer[0] = x;
  32164. UniformBuffer._tempBuffer[1] = y;
  32165. UniformBuffer._tempBuffer[2] = z;
  32166. UniformBuffer._tempBuffer[3] = w;
  32167. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32168. };
  32169. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32170. this._currentEffect.setMatrix(name, mat);
  32171. };
  32172. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32173. this.updateUniform(name, mat.toArray(), 16);
  32174. };
  32175. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32176. this._currentEffect.setVector3(name, vector);
  32177. };
  32178. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32179. vector.toArray(UniformBuffer._tempBuffer);
  32180. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32181. };
  32182. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32183. this._currentEffect.setVector4(name, vector);
  32184. };
  32185. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32186. vector.toArray(UniformBuffer._tempBuffer);
  32187. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32188. };
  32189. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32190. if (suffix === void 0) { suffix = ""; }
  32191. this._currentEffect.setColor3(name + suffix, color);
  32192. };
  32193. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32194. if (suffix === void 0) { suffix = ""; }
  32195. color.toArray(UniformBuffer._tempBuffer);
  32196. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32197. };
  32198. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32199. if (suffix === void 0) { suffix = ""; }
  32200. this._currentEffect.setColor4(name + suffix, color, alpha);
  32201. };
  32202. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32203. if (suffix === void 0) { suffix = ""; }
  32204. color.toArray(UniformBuffer._tempBuffer);
  32205. UniformBuffer._tempBuffer[3] = alpha;
  32206. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32207. };
  32208. /**
  32209. * Sets a sampler uniform on the effect.
  32210. * @param {string} name Name of the sampler.
  32211. * @param {Texture} texture
  32212. */
  32213. UniformBuffer.prototype.setTexture = function (name, texture) {
  32214. this._currentEffect.setTexture(name, texture);
  32215. };
  32216. /**
  32217. * Directly updates the value of the uniform in the cache AND on the GPU.
  32218. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32219. * @param {number[]|Float32Array} data Flattened data
  32220. */
  32221. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32222. this.updateUniform(uniformName, data, data.length);
  32223. this.update();
  32224. };
  32225. /**
  32226. * Binds this uniform buffer to an effect.
  32227. * @param {Effect} effect
  32228. * @param {string} name Name of the uniform block in the shader.
  32229. */
  32230. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32231. this._currentEffect = effect;
  32232. if (this._noUBO || !this._buffer) {
  32233. return;
  32234. }
  32235. effect.bindUniformBuffer(this._buffer, name);
  32236. };
  32237. /**
  32238. * Disposes the uniform buffer.
  32239. */
  32240. UniformBuffer.prototype.dispose = function () {
  32241. if (this._noUBO) {
  32242. return;
  32243. }
  32244. var index = this._engine._uniformBuffers.indexOf(this);
  32245. if (index !== -1) {
  32246. this._engine._uniformBuffers.splice(index, 1);
  32247. }
  32248. if (!this._buffer) {
  32249. return;
  32250. }
  32251. if (this._engine._releaseBuffer(this._buffer)) {
  32252. this._buffer = null;
  32253. }
  32254. };
  32255. // Pool for avoiding memory leaks
  32256. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32257. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32258. return UniformBuffer;
  32259. }());
  32260. BABYLON.UniformBuffer = UniformBuffer;
  32261. })(BABYLON || (BABYLON = {}));
  32262. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32263. var BABYLON;
  32264. (function (BABYLON) {
  32265. var VertexData = /** @class */ (function () {
  32266. function VertexData() {
  32267. }
  32268. VertexData.prototype.set = function (data, kind) {
  32269. switch (kind) {
  32270. case BABYLON.VertexBuffer.PositionKind:
  32271. this.positions = data;
  32272. break;
  32273. case BABYLON.VertexBuffer.NormalKind:
  32274. this.normals = data;
  32275. break;
  32276. case BABYLON.VertexBuffer.TangentKind:
  32277. this.tangents = data;
  32278. break;
  32279. case BABYLON.VertexBuffer.UVKind:
  32280. this.uvs = data;
  32281. break;
  32282. case BABYLON.VertexBuffer.UV2Kind:
  32283. this.uvs2 = data;
  32284. break;
  32285. case BABYLON.VertexBuffer.UV3Kind:
  32286. this.uvs3 = data;
  32287. break;
  32288. case BABYLON.VertexBuffer.UV4Kind:
  32289. this.uvs4 = data;
  32290. break;
  32291. case BABYLON.VertexBuffer.UV5Kind:
  32292. this.uvs5 = data;
  32293. break;
  32294. case BABYLON.VertexBuffer.UV6Kind:
  32295. this.uvs6 = data;
  32296. break;
  32297. case BABYLON.VertexBuffer.ColorKind:
  32298. this.colors = data;
  32299. break;
  32300. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32301. this.matricesIndices = data;
  32302. break;
  32303. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32304. this.matricesWeights = data;
  32305. break;
  32306. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32307. this.matricesIndicesExtra = data;
  32308. break;
  32309. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32310. this.matricesWeightsExtra = data;
  32311. break;
  32312. }
  32313. };
  32314. /**
  32315. * Associates the vertexData to the passed Mesh.
  32316. * Sets it as updatable or not (default `false`).
  32317. * Returns the VertexData.
  32318. */
  32319. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32320. this._applyTo(mesh, updatable);
  32321. return this;
  32322. };
  32323. /**
  32324. * Associates the vertexData to the passed Geometry.
  32325. * Sets it as updatable or not (default `false`).
  32326. * Returns the VertexData.
  32327. */
  32328. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32329. this._applyTo(geometry, updatable);
  32330. return this;
  32331. };
  32332. /**
  32333. * Updates the associated mesh.
  32334. * Returns the VertexData.
  32335. */
  32336. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32337. this._update(mesh);
  32338. return this;
  32339. };
  32340. /**
  32341. * Updates the associated geometry.
  32342. * Returns the VertexData.
  32343. */
  32344. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32345. this._update(geometry);
  32346. return this;
  32347. };
  32348. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32349. if (updatable === void 0) { updatable = false; }
  32350. if (this.positions) {
  32351. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32352. }
  32353. if (this.normals) {
  32354. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32355. }
  32356. if (this.tangents) {
  32357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32358. }
  32359. if (this.uvs) {
  32360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32361. }
  32362. if (this.uvs2) {
  32363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32364. }
  32365. if (this.uvs3) {
  32366. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32367. }
  32368. if (this.uvs4) {
  32369. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32370. }
  32371. if (this.uvs5) {
  32372. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32373. }
  32374. if (this.uvs6) {
  32375. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32376. }
  32377. if (this.colors) {
  32378. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32379. }
  32380. if (this.matricesIndices) {
  32381. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32382. }
  32383. if (this.matricesWeights) {
  32384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32385. }
  32386. if (this.matricesIndicesExtra) {
  32387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32388. }
  32389. if (this.matricesWeightsExtra) {
  32390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32391. }
  32392. if (this.indices) {
  32393. meshOrGeometry.setIndices(this.indices, null, updatable);
  32394. }
  32395. return this;
  32396. };
  32397. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32398. if (this.positions) {
  32399. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32400. }
  32401. if (this.normals) {
  32402. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32403. }
  32404. if (this.tangents) {
  32405. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32406. }
  32407. if (this.uvs) {
  32408. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32409. }
  32410. if (this.uvs2) {
  32411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32412. }
  32413. if (this.uvs3) {
  32414. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32415. }
  32416. if (this.uvs4) {
  32417. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32418. }
  32419. if (this.uvs5) {
  32420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32421. }
  32422. if (this.uvs6) {
  32423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32424. }
  32425. if (this.colors) {
  32426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32427. }
  32428. if (this.matricesIndices) {
  32429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32430. }
  32431. if (this.matricesWeights) {
  32432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32433. }
  32434. if (this.matricesIndicesExtra) {
  32435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32436. }
  32437. if (this.matricesWeightsExtra) {
  32438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32439. }
  32440. if (this.indices) {
  32441. meshOrGeometry.setIndices(this.indices, null);
  32442. }
  32443. return this;
  32444. };
  32445. /**
  32446. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32447. * Returns the VertexData.
  32448. */
  32449. VertexData.prototype.transform = function (matrix) {
  32450. var transformed = BABYLON.Vector3.Zero();
  32451. var index;
  32452. if (this.positions) {
  32453. var position = BABYLON.Vector3.Zero();
  32454. for (index = 0; index < this.positions.length; index += 3) {
  32455. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32456. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32457. this.positions[index] = transformed.x;
  32458. this.positions[index + 1] = transformed.y;
  32459. this.positions[index + 2] = transformed.z;
  32460. }
  32461. }
  32462. if (this.normals) {
  32463. var normal = BABYLON.Vector3.Zero();
  32464. for (index = 0; index < this.normals.length; index += 3) {
  32465. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32466. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32467. this.normals[index] = transformed.x;
  32468. this.normals[index + 1] = transformed.y;
  32469. this.normals[index + 2] = transformed.z;
  32470. }
  32471. }
  32472. if (this.tangents) {
  32473. var tangent = BABYLON.Vector4.Zero();
  32474. var tangentTransformed = BABYLON.Vector4.Zero();
  32475. for (index = 0; index < this.tangents.length; index += 4) {
  32476. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32477. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32478. this.tangents[index] = tangentTransformed.x;
  32479. this.tangents[index + 1] = tangentTransformed.y;
  32480. this.tangents[index + 2] = tangentTransformed.z;
  32481. this.tangents[index + 3] = tangentTransformed.w;
  32482. }
  32483. }
  32484. return this;
  32485. };
  32486. /**
  32487. * Merges the passed VertexData into the current one.
  32488. * Returns the modified VertexData.
  32489. */
  32490. VertexData.prototype.merge = function (other) {
  32491. this._validate();
  32492. other._validate();
  32493. if (!this.normals !== !other.normals ||
  32494. !this.tangents !== !other.tangents ||
  32495. !this.uvs !== !other.uvs ||
  32496. !this.uvs2 !== !other.uvs2 ||
  32497. !this.uvs3 !== !other.uvs3 ||
  32498. !this.uvs4 !== !other.uvs4 ||
  32499. !this.uvs5 !== !other.uvs5 ||
  32500. !this.uvs6 !== !other.uvs6 ||
  32501. !this.colors !== !other.colors ||
  32502. !this.matricesIndices !== !other.matricesIndices ||
  32503. !this.matricesWeights !== !other.matricesWeights ||
  32504. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32505. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32506. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32507. }
  32508. if (other.indices) {
  32509. if (!this.indices) {
  32510. this.indices = [];
  32511. }
  32512. var offset = this.positions ? this.positions.length / 3 : 0;
  32513. for (var index = 0; index < other.indices.length; index++) {
  32514. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32515. this.indices.push(other.indices[index] + offset);
  32516. }
  32517. }
  32518. this.positions = this._mergeElement(this.positions, other.positions);
  32519. this.normals = this._mergeElement(this.normals, other.normals);
  32520. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32521. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32522. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32523. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32524. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32525. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32526. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32527. this.colors = this._mergeElement(this.colors, other.colors);
  32528. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32529. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32530. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32531. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32532. return this;
  32533. };
  32534. VertexData.prototype._mergeElement = function (source, other) {
  32535. if (!source) {
  32536. return other;
  32537. }
  32538. if (!other) {
  32539. return source;
  32540. }
  32541. var len = other.length + source.length;
  32542. var isSrcTypedArray = source instanceof Float32Array;
  32543. var isOthTypedArray = other instanceof Float32Array;
  32544. // use non-loop method when the source is Float32Array
  32545. if (isSrcTypedArray) {
  32546. var ret32 = new Float32Array(len);
  32547. ret32.set(source);
  32548. ret32.set(other, source.length);
  32549. return ret32;
  32550. // source is number[], when other is also use concat
  32551. }
  32552. else if (!isOthTypedArray) {
  32553. return source.concat(other);
  32554. // source is a number[], but other is a Float32Array, loop required
  32555. }
  32556. else {
  32557. var ret = source.slice(0); // copy source to a separate array
  32558. for (var i = 0, len = other.length; i < len; i++) {
  32559. ret.push(other[i]);
  32560. }
  32561. return ret;
  32562. }
  32563. };
  32564. VertexData.prototype._validate = function () {
  32565. if (!this.positions) {
  32566. throw new Error("Positions are required");
  32567. }
  32568. var getElementCount = function (kind, values) {
  32569. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32570. if ((values.length % stride) !== 0) {
  32571. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32572. }
  32573. return values.length / stride;
  32574. };
  32575. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32576. var validateElementCount = function (kind, values) {
  32577. var elementCount = getElementCount(kind, values);
  32578. if (elementCount !== positionsElementCount) {
  32579. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32580. }
  32581. };
  32582. if (this.normals)
  32583. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32584. if (this.tangents)
  32585. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32586. if (this.uvs)
  32587. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32588. if (this.uvs2)
  32589. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32590. if (this.uvs3)
  32591. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32592. if (this.uvs4)
  32593. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32594. if (this.uvs5)
  32595. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32596. if (this.uvs6)
  32597. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32598. if (this.colors)
  32599. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32600. if (this.matricesIndices)
  32601. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32602. if (this.matricesWeights)
  32603. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32604. if (this.matricesIndicesExtra)
  32605. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32606. if (this.matricesWeightsExtra)
  32607. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32608. };
  32609. /**
  32610. * Serializes the VertexData.
  32611. * Returns a serialized object.
  32612. */
  32613. VertexData.prototype.serialize = function () {
  32614. var serializationObject = this.serialize();
  32615. if (this.positions) {
  32616. serializationObject.positions = this.positions;
  32617. }
  32618. if (this.normals) {
  32619. serializationObject.normals = this.normals;
  32620. }
  32621. if (this.tangents) {
  32622. serializationObject.tangents = this.tangents;
  32623. }
  32624. if (this.uvs) {
  32625. serializationObject.uvs = this.uvs;
  32626. }
  32627. if (this.uvs2) {
  32628. serializationObject.uvs2 = this.uvs2;
  32629. }
  32630. if (this.uvs3) {
  32631. serializationObject.uvs3 = this.uvs3;
  32632. }
  32633. if (this.uvs4) {
  32634. serializationObject.uvs4 = this.uvs4;
  32635. }
  32636. if (this.uvs5) {
  32637. serializationObject.uvs5 = this.uvs5;
  32638. }
  32639. if (this.uvs6) {
  32640. serializationObject.uvs6 = this.uvs6;
  32641. }
  32642. if (this.colors) {
  32643. serializationObject.colors = this.colors;
  32644. }
  32645. if (this.matricesIndices) {
  32646. serializationObject.matricesIndices = this.matricesIndices;
  32647. serializationObject.matricesIndices._isExpanded = true;
  32648. }
  32649. if (this.matricesWeights) {
  32650. serializationObject.matricesWeights = this.matricesWeights;
  32651. }
  32652. if (this.matricesIndicesExtra) {
  32653. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32654. serializationObject.matricesIndicesExtra._isExpanded = true;
  32655. }
  32656. if (this.matricesWeightsExtra) {
  32657. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32658. }
  32659. serializationObject.indices = this.indices;
  32660. return serializationObject;
  32661. };
  32662. // Statics
  32663. /**
  32664. * Returns the object VertexData associated to the passed mesh.
  32665. */
  32666. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32667. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32668. };
  32669. /**
  32670. * Returns the object VertexData associated to the passed geometry.
  32671. */
  32672. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32673. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32674. };
  32675. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32676. var result = new VertexData();
  32677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32678. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32679. }
  32680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32681. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32682. }
  32683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32684. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32685. }
  32686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32687. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32688. }
  32689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32690. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32691. }
  32692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32693. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32694. }
  32695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32696. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32697. }
  32698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32699. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32700. }
  32701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32702. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32703. }
  32704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32705. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32706. }
  32707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32708. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32709. }
  32710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32711. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32712. }
  32713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32714. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32715. }
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32717. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32718. }
  32719. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32720. return result;
  32721. };
  32722. /**
  32723. * Creates the vertexData of the Ribbon.
  32724. */
  32725. VertexData.CreateRibbon = function (options) {
  32726. var pathArray = options.pathArray;
  32727. var closeArray = options.closeArray || false;
  32728. var closePath = options.closePath || false;
  32729. var invertUV = options.invertUV || false;
  32730. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32731. var offset = options.offset || defaultOffset;
  32732. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32734. var customUV = options.uvs;
  32735. var customColors = options.colors;
  32736. var positions = [];
  32737. var indices = [];
  32738. var normals = [];
  32739. var uvs = [];
  32740. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32741. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32742. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32743. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32744. var minlg; // minimal length among all paths from pathArray
  32745. var lg = []; // array of path lengths : nb of vertex per path
  32746. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32747. var p; // path iterator
  32748. var i; // point iterator
  32749. var j; // point iterator
  32750. // if single path in pathArray
  32751. if (pathArray.length < 2) {
  32752. var ar1 = [];
  32753. var ar2 = [];
  32754. for (i = 0; i < pathArray[0].length - offset; i++) {
  32755. ar1.push(pathArray[0][i]);
  32756. ar2.push(pathArray[0][i + offset]);
  32757. }
  32758. pathArray = [ar1, ar2];
  32759. }
  32760. // positions and horizontal distances (u)
  32761. var idc = 0;
  32762. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32763. var path;
  32764. var l;
  32765. minlg = pathArray[0].length;
  32766. var vectlg;
  32767. var dist;
  32768. for (p = 0; p < pathArray.length; p++) {
  32769. uTotalDistance[p] = 0;
  32770. us[p] = [0];
  32771. path = pathArray[p];
  32772. l = path.length;
  32773. minlg = (minlg < l) ? minlg : l;
  32774. j = 0;
  32775. while (j < l) {
  32776. positions.push(path[j].x, path[j].y, path[j].z);
  32777. if (j > 0) {
  32778. vectlg = path[j].subtract(path[j - 1]).length();
  32779. dist = vectlg + uTotalDistance[p];
  32780. us[p].push(dist);
  32781. uTotalDistance[p] = dist;
  32782. }
  32783. j++;
  32784. }
  32785. if (closePath) {
  32786. j--;
  32787. positions.push(path[0].x, path[0].y, path[0].z);
  32788. vectlg = path[j].subtract(path[0]).length();
  32789. dist = vectlg + uTotalDistance[p];
  32790. us[p].push(dist);
  32791. uTotalDistance[p] = dist;
  32792. }
  32793. lg[p] = l + closePathCorr;
  32794. idx[p] = idc;
  32795. idc += (l + closePathCorr);
  32796. }
  32797. // vertical distances (v)
  32798. var path1;
  32799. var path2;
  32800. var vertex1 = null;
  32801. var vertex2 = null;
  32802. for (i = 0; i < minlg + closePathCorr; i++) {
  32803. vTotalDistance[i] = 0;
  32804. vs[i] = [0];
  32805. for (p = 0; p < pathArray.length - 1; p++) {
  32806. path1 = pathArray[p];
  32807. path2 = pathArray[p + 1];
  32808. if (i === minlg) {
  32809. vertex1 = path1[0];
  32810. vertex2 = path2[0];
  32811. }
  32812. else {
  32813. vertex1 = path1[i];
  32814. vertex2 = path2[i];
  32815. }
  32816. vectlg = vertex2.subtract(vertex1).length();
  32817. dist = vectlg + vTotalDistance[i];
  32818. vs[i].push(dist);
  32819. vTotalDistance[i] = dist;
  32820. }
  32821. if (closeArray && vertex2 && vertex1) {
  32822. path1 = pathArray[p];
  32823. path2 = pathArray[0];
  32824. if (i === minlg) {
  32825. vertex2 = path2[0];
  32826. }
  32827. vectlg = vertex2.subtract(vertex1).length();
  32828. dist = vectlg + vTotalDistance[i];
  32829. vTotalDistance[i] = dist;
  32830. }
  32831. }
  32832. // uvs
  32833. var u;
  32834. var v;
  32835. if (customUV) {
  32836. for (p = 0; p < customUV.length; p++) {
  32837. uvs.push(customUV[p].x, customUV[p].y);
  32838. }
  32839. }
  32840. else {
  32841. for (p = 0; p < pathArray.length; p++) {
  32842. for (i = 0; i < minlg + closePathCorr; i++) {
  32843. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32844. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32845. if (invertUV) {
  32846. uvs.push(v, u);
  32847. }
  32848. else {
  32849. uvs.push(u, v);
  32850. }
  32851. }
  32852. }
  32853. }
  32854. // indices
  32855. p = 0; // path index
  32856. var pi = 0; // positions array index
  32857. var l1 = lg[p] - 1; // path1 length
  32858. var l2 = lg[p + 1] - 1; // path2 length
  32859. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32860. var shft = idx[1] - idx[0]; // shift
  32861. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32862. while (pi <= min && p < path1nb) {
  32863. // 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
  32864. indices.push(pi, pi + shft, pi + 1);
  32865. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32866. pi += 1;
  32867. if (pi === min) {
  32868. p++;
  32869. if (p === lg.length - 1) {
  32870. shft = idx[0] - idx[p];
  32871. l1 = lg[p] - 1;
  32872. l2 = lg[0] - 1;
  32873. }
  32874. else {
  32875. shft = idx[p + 1] - idx[p];
  32876. l1 = lg[p] - 1;
  32877. l2 = lg[p + 1] - 1;
  32878. }
  32879. pi = idx[p];
  32880. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32881. }
  32882. }
  32883. // normals
  32884. VertexData.ComputeNormals(positions, indices, normals);
  32885. if (closePath) {
  32886. var indexFirst = 0;
  32887. var indexLast = 0;
  32888. for (p = 0; p < pathArray.length; p++) {
  32889. indexFirst = idx[p] * 3;
  32890. if (p + 1 < pathArray.length) {
  32891. indexLast = (idx[p + 1] - 1) * 3;
  32892. }
  32893. else {
  32894. indexLast = normals.length - 3;
  32895. }
  32896. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32897. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32898. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32899. normals[indexLast] = normals[indexFirst];
  32900. normals[indexLast + 1] = normals[indexFirst + 1];
  32901. normals[indexLast + 2] = normals[indexFirst + 2];
  32902. }
  32903. }
  32904. // sides
  32905. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32906. // Colors
  32907. var colors = null;
  32908. if (customColors) {
  32909. colors = new Float32Array(customColors.length * 4);
  32910. for (var c = 0; c < customColors.length; c++) {
  32911. colors[c * 4] = customColors[c].r;
  32912. colors[c * 4 + 1] = customColors[c].g;
  32913. colors[c * 4 + 2] = customColors[c].b;
  32914. colors[c * 4 + 3] = customColors[c].a;
  32915. }
  32916. }
  32917. // Result
  32918. var vertexData = new VertexData();
  32919. var positions32 = new Float32Array(positions);
  32920. var normals32 = new Float32Array(normals);
  32921. var uvs32 = new Float32Array(uvs);
  32922. vertexData.indices = indices;
  32923. vertexData.positions = positions32;
  32924. vertexData.normals = normals32;
  32925. vertexData.uvs = uvs32;
  32926. if (colors) {
  32927. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32928. }
  32929. if (closePath) {
  32930. vertexData._idx = idx;
  32931. }
  32932. return vertexData;
  32933. };
  32934. /**
  32935. * Creates the VertexData of the Box.
  32936. */
  32937. VertexData.CreateBox = function (options) {
  32938. var normalsSource = [
  32939. new BABYLON.Vector3(0, 0, 1),
  32940. new BABYLON.Vector3(0, 0, -1),
  32941. new BABYLON.Vector3(1, 0, 0),
  32942. new BABYLON.Vector3(-1, 0, 0),
  32943. new BABYLON.Vector3(0, 1, 0),
  32944. new BABYLON.Vector3(0, -1, 0)
  32945. ];
  32946. var indices = [];
  32947. var positions = [];
  32948. var normals = [];
  32949. var uvs = [];
  32950. var width = options.width || options.size || 1;
  32951. var height = options.height || options.size || 1;
  32952. var depth = options.depth || options.size || 1;
  32953. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32954. var faceUV = options.faceUV || new Array(6);
  32955. var faceColors = options.faceColors;
  32956. var colors = [];
  32957. // default face colors and UV if undefined
  32958. for (var f = 0; f < 6; f++) {
  32959. if (faceUV[f] === undefined) {
  32960. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32961. }
  32962. if (faceColors && faceColors[f] === undefined) {
  32963. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32964. }
  32965. }
  32966. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32967. // Create each face in turn.
  32968. for (var index = 0; index < normalsSource.length; index++) {
  32969. var normal = normalsSource[index];
  32970. // Get two vectors perpendicular to the face normal and to each other.
  32971. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32972. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32973. // Six indices (two triangles) per face.
  32974. var verticesLength = positions.length / 3;
  32975. indices.push(verticesLength);
  32976. indices.push(verticesLength + 1);
  32977. indices.push(verticesLength + 2);
  32978. indices.push(verticesLength);
  32979. indices.push(verticesLength + 2);
  32980. indices.push(verticesLength + 3);
  32981. // Four vertices per face.
  32982. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32983. positions.push(vertex.x, vertex.y, vertex.z);
  32984. normals.push(normal.x, normal.y, normal.z);
  32985. uvs.push(faceUV[index].z, faceUV[index].w);
  32986. if (faceColors) {
  32987. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32988. }
  32989. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32990. positions.push(vertex.x, vertex.y, vertex.z);
  32991. normals.push(normal.x, normal.y, normal.z);
  32992. uvs.push(faceUV[index].x, faceUV[index].w);
  32993. if (faceColors) {
  32994. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32995. }
  32996. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32997. positions.push(vertex.x, vertex.y, vertex.z);
  32998. normals.push(normal.x, normal.y, normal.z);
  32999. uvs.push(faceUV[index].x, faceUV[index].y);
  33000. if (faceColors) {
  33001. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33002. }
  33003. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33004. positions.push(vertex.x, vertex.y, vertex.z);
  33005. normals.push(normal.x, normal.y, normal.z);
  33006. uvs.push(faceUV[index].z, faceUV[index].y);
  33007. if (faceColors) {
  33008. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33009. }
  33010. }
  33011. // sides
  33012. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33013. // Result
  33014. var vertexData = new VertexData();
  33015. vertexData.indices = indices;
  33016. vertexData.positions = positions;
  33017. vertexData.normals = normals;
  33018. vertexData.uvs = uvs;
  33019. if (faceColors) {
  33020. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33021. vertexData.colors = totalColors;
  33022. }
  33023. return vertexData;
  33024. };
  33025. /**
  33026. * Creates the VertexData of the Sphere.
  33027. */
  33028. VertexData.CreateSphere = function (options) {
  33029. var segments = options.segments || 32;
  33030. var diameterX = options.diameterX || options.diameter || 1;
  33031. var diameterY = options.diameterY || options.diameter || 1;
  33032. var diameterZ = options.diameterZ || options.diameter || 1;
  33033. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33034. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33036. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33037. var totalZRotationSteps = 2 + segments;
  33038. var totalYRotationSteps = 2 * totalZRotationSteps;
  33039. var indices = [];
  33040. var positions = [];
  33041. var normals = [];
  33042. var uvs = [];
  33043. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33044. var normalizedZ = zRotationStep / totalZRotationSteps;
  33045. var angleZ = normalizedZ * Math.PI * slice;
  33046. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33047. var normalizedY = yRotationStep / totalYRotationSteps;
  33048. var angleY = normalizedY * Math.PI * 2 * arc;
  33049. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33050. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33051. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33052. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33053. var vertex = complete.multiply(radius);
  33054. var normal = complete.divide(radius).normalize();
  33055. positions.push(vertex.x, vertex.y, vertex.z);
  33056. normals.push(normal.x, normal.y, normal.z);
  33057. uvs.push(normalizedY, normalizedZ);
  33058. }
  33059. if (zRotationStep > 0) {
  33060. var verticesCount = positions.length / 3;
  33061. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33062. indices.push((firstIndex));
  33063. indices.push((firstIndex + 1));
  33064. indices.push(firstIndex + totalYRotationSteps + 1);
  33065. indices.push((firstIndex + totalYRotationSteps + 1));
  33066. indices.push((firstIndex + 1));
  33067. indices.push((firstIndex + totalYRotationSteps + 2));
  33068. }
  33069. }
  33070. }
  33071. // Sides
  33072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33073. // Result
  33074. var vertexData = new VertexData();
  33075. vertexData.indices = indices;
  33076. vertexData.positions = positions;
  33077. vertexData.normals = normals;
  33078. vertexData.uvs = uvs;
  33079. return vertexData;
  33080. };
  33081. /**
  33082. * Creates the VertexData of the Cylinder or Cone.
  33083. */
  33084. VertexData.CreateCylinder = function (options) {
  33085. var height = options.height || 2;
  33086. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33087. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33088. var tessellation = options.tessellation || 24;
  33089. var subdivisions = options.subdivisions || 1;
  33090. var hasRings = options.hasRings ? true : false;
  33091. var enclose = options.enclose ? true : false;
  33092. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33093. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33094. var faceUV = options.faceUV || new Array(3);
  33095. var faceColors = options.faceColors;
  33096. // default face colors and UV if undefined
  33097. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33098. var ringNb = (hasRings) ? subdivisions : 1;
  33099. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33100. var f;
  33101. for (f = 0; f < surfaceNb; f++) {
  33102. if (faceColors && faceColors[f] === undefined) {
  33103. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33104. }
  33105. }
  33106. for (f = 0; f < surfaceNb; f++) {
  33107. if (faceUV && faceUV[f] === undefined) {
  33108. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33109. }
  33110. }
  33111. var indices = new Array();
  33112. var positions = new Array();
  33113. var normals = new Array();
  33114. var uvs = new Array();
  33115. var colors = new Array();
  33116. var angle_step = Math.PI * 2 * arc / tessellation;
  33117. var angle;
  33118. var h;
  33119. var radius;
  33120. var tan = (diameterBottom - diameterTop) / 2 / height;
  33121. var ringVertex = BABYLON.Vector3.Zero();
  33122. var ringNormal = BABYLON.Vector3.Zero();
  33123. var ringFirstVertex = BABYLON.Vector3.Zero();
  33124. var ringFirstNormal = BABYLON.Vector3.Zero();
  33125. var quadNormal = BABYLON.Vector3.Zero();
  33126. var Y = BABYLON.Axis.Y;
  33127. // positions, normals, uvs
  33128. var i;
  33129. var j;
  33130. var r;
  33131. var ringIdx = 1;
  33132. var s = 1; // surface index
  33133. var cs = 0;
  33134. var v = 0;
  33135. for (i = 0; i <= subdivisions; i++) {
  33136. h = i / subdivisions;
  33137. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33138. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33139. for (r = 0; r < ringIdx; r++) {
  33140. if (hasRings) {
  33141. s += r;
  33142. }
  33143. if (enclose) {
  33144. s += 2 * r;
  33145. }
  33146. for (j = 0; j <= tessellation; j++) {
  33147. angle = j * angle_step;
  33148. // position
  33149. ringVertex.x = Math.cos(-angle) * radius;
  33150. ringVertex.y = -height / 2 + h * height;
  33151. ringVertex.z = Math.sin(-angle) * radius;
  33152. // normal
  33153. if (diameterTop === 0 && i === subdivisions) {
  33154. // if no top cap, reuse former normals
  33155. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33156. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33157. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33158. }
  33159. else {
  33160. ringNormal.x = ringVertex.x;
  33161. ringNormal.z = ringVertex.z;
  33162. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33163. ringNormal.normalize();
  33164. }
  33165. // keep first ring vertex values for enclose
  33166. if (j === 0) {
  33167. ringFirstVertex.copyFrom(ringVertex);
  33168. ringFirstNormal.copyFrom(ringNormal);
  33169. }
  33170. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33171. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33172. if (hasRings) {
  33173. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33174. }
  33175. else {
  33176. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33177. }
  33178. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33179. if (faceColors) {
  33180. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33181. }
  33182. }
  33183. // if enclose, add four vertices and their dedicated normals
  33184. if (arc !== 1 && enclose) {
  33185. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33186. positions.push(0, ringVertex.y, 0);
  33187. positions.push(0, ringVertex.y, 0);
  33188. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33189. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33190. quadNormal.normalize();
  33191. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33192. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33193. quadNormal.normalize();
  33194. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33195. if (hasRings) {
  33196. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33197. }
  33198. else {
  33199. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33200. }
  33201. uvs.push(faceUV[s + 1].x, v);
  33202. uvs.push(faceUV[s + 1].z, v);
  33203. if (hasRings) {
  33204. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33205. }
  33206. else {
  33207. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33208. }
  33209. uvs.push(faceUV[s + 2].x, v);
  33210. uvs.push(faceUV[s + 2].z, v);
  33211. if (faceColors) {
  33212. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33213. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33214. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33215. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33216. }
  33217. }
  33218. if (cs !== s) {
  33219. cs = s;
  33220. }
  33221. }
  33222. }
  33223. // indices
  33224. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33225. var s;
  33226. i = 0;
  33227. for (s = 0; s < subdivisions; s++) {
  33228. var i0 = 0;
  33229. var i1 = 0;
  33230. var i2 = 0;
  33231. var i3 = 0;
  33232. for (j = 0; j < tessellation; j++) {
  33233. i0 = i * (e + 1) + j;
  33234. i1 = (i + 1) * (e + 1) + j;
  33235. i2 = i * (e + 1) + (j + 1);
  33236. i3 = (i + 1) * (e + 1) + (j + 1);
  33237. indices.push(i0, i1, i2);
  33238. indices.push(i3, i2, i1);
  33239. }
  33240. if (arc !== 1 && enclose) {
  33241. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33242. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33243. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33244. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33245. }
  33246. i = (hasRings) ? (i + 2) : (i + 1);
  33247. }
  33248. // Caps
  33249. var createCylinderCap = function (isTop) {
  33250. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33251. if (radius === 0) {
  33252. return;
  33253. }
  33254. // Cap positions, normals & uvs
  33255. var angle;
  33256. var circleVector;
  33257. var i;
  33258. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33259. var c = null;
  33260. if (faceColors) {
  33261. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33262. }
  33263. // cap center
  33264. var vbase = positions.length / 3;
  33265. var offset = isTop ? height / 2 : -height / 2;
  33266. var center = new BABYLON.Vector3(0, offset, 0);
  33267. positions.push(center.x, center.y, center.z);
  33268. normals.push(0, isTop ? 1 : -1, 0);
  33269. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33270. if (c) {
  33271. colors.push(c.r, c.g, c.b, c.a);
  33272. }
  33273. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33274. for (i = 0; i <= tessellation; i++) {
  33275. angle = Math.PI * 2 * i * arc / tessellation;
  33276. var cos = Math.cos(-angle);
  33277. var sin = Math.sin(-angle);
  33278. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33279. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33280. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33281. normals.push(0, isTop ? 1 : -1, 0);
  33282. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33283. if (c) {
  33284. colors.push(c.r, c.g, c.b, c.a);
  33285. }
  33286. }
  33287. // Cap indices
  33288. for (i = 0; i < tessellation; i++) {
  33289. if (!isTop) {
  33290. indices.push(vbase);
  33291. indices.push(vbase + (i + 1));
  33292. indices.push(vbase + (i + 2));
  33293. }
  33294. else {
  33295. indices.push(vbase);
  33296. indices.push(vbase + (i + 2));
  33297. indices.push(vbase + (i + 1));
  33298. }
  33299. }
  33300. };
  33301. // add caps to geometry
  33302. createCylinderCap(false);
  33303. createCylinderCap(true);
  33304. // Sides
  33305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33306. var vertexData = new VertexData();
  33307. vertexData.indices = indices;
  33308. vertexData.positions = positions;
  33309. vertexData.normals = normals;
  33310. vertexData.uvs = uvs;
  33311. if (faceColors) {
  33312. vertexData.colors = colors;
  33313. }
  33314. return vertexData;
  33315. };
  33316. /**
  33317. * Creates the VertexData of the Torus.
  33318. */
  33319. VertexData.CreateTorus = function (options) {
  33320. var indices = [];
  33321. var positions = [];
  33322. var normals = [];
  33323. var uvs = [];
  33324. var diameter = options.diameter || 1;
  33325. var thickness = options.thickness || 0.5;
  33326. var tessellation = options.tessellation || 16;
  33327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33328. var stride = tessellation + 1;
  33329. for (var i = 0; i <= tessellation; i++) {
  33330. var u = i / tessellation;
  33331. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33332. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33333. for (var j = 0; j <= tessellation; j++) {
  33334. var v = 1 - j / tessellation;
  33335. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33336. var dx = Math.cos(innerAngle);
  33337. var dy = Math.sin(innerAngle);
  33338. // Create a vertex.
  33339. var normal = new BABYLON.Vector3(dx, dy, 0);
  33340. var position = normal.scale(thickness / 2);
  33341. var textureCoordinate = new BABYLON.Vector2(u, v);
  33342. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33343. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33344. positions.push(position.x, position.y, position.z);
  33345. normals.push(normal.x, normal.y, normal.z);
  33346. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33347. // And create indices for two triangles.
  33348. var nextI = (i + 1) % stride;
  33349. var nextJ = (j + 1) % stride;
  33350. indices.push(i * stride + j);
  33351. indices.push(i * stride + nextJ);
  33352. indices.push(nextI * stride + j);
  33353. indices.push(i * stride + nextJ);
  33354. indices.push(nextI * stride + nextJ);
  33355. indices.push(nextI * stride + j);
  33356. }
  33357. }
  33358. // Sides
  33359. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33360. // Result
  33361. var vertexData = new VertexData();
  33362. vertexData.indices = indices;
  33363. vertexData.positions = positions;
  33364. vertexData.normals = normals;
  33365. vertexData.uvs = uvs;
  33366. return vertexData;
  33367. };
  33368. /**
  33369. * Creates the VertexData of the LineSystem.
  33370. */
  33371. VertexData.CreateLineSystem = function (options) {
  33372. var indices = [];
  33373. var positions = [];
  33374. var lines = options.lines;
  33375. var colors = options.colors;
  33376. var vertexColors = [];
  33377. var idx = 0;
  33378. for (var l = 0; l < lines.length; l++) {
  33379. var points = lines[l];
  33380. for (var index = 0; index < points.length; index++) {
  33381. positions.push(points[index].x, points[index].y, points[index].z);
  33382. if (colors) {
  33383. var color = colors[l];
  33384. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33385. }
  33386. if (index > 0) {
  33387. indices.push(idx - 1);
  33388. indices.push(idx);
  33389. }
  33390. idx++;
  33391. }
  33392. }
  33393. var vertexData = new VertexData();
  33394. vertexData.indices = indices;
  33395. vertexData.positions = positions;
  33396. if (colors) {
  33397. vertexData.colors = vertexColors;
  33398. }
  33399. return vertexData;
  33400. };
  33401. /**
  33402. * Create the VertexData of the DashedLines.
  33403. */
  33404. VertexData.CreateDashedLines = function (options) {
  33405. var dashSize = options.dashSize || 3;
  33406. var gapSize = options.gapSize || 1;
  33407. var dashNb = options.dashNb || 200;
  33408. var points = options.points;
  33409. var positions = new Array();
  33410. var indices = new Array();
  33411. var curvect = BABYLON.Vector3.Zero();
  33412. var lg = 0;
  33413. var nb = 0;
  33414. var shft = 0;
  33415. var dashshft = 0;
  33416. var curshft = 0;
  33417. var idx = 0;
  33418. var i = 0;
  33419. for (i = 0; i < points.length - 1; i++) {
  33420. points[i + 1].subtractToRef(points[i], curvect);
  33421. lg += curvect.length();
  33422. }
  33423. shft = lg / dashNb;
  33424. dashshft = dashSize * shft / (dashSize + gapSize);
  33425. for (i = 0; i < points.length - 1; i++) {
  33426. points[i + 1].subtractToRef(points[i], curvect);
  33427. nb = Math.floor(curvect.length() / shft);
  33428. curvect.normalize();
  33429. for (var j = 0; j < nb; j++) {
  33430. curshft = shft * j;
  33431. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33432. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33433. indices.push(idx, idx + 1);
  33434. idx += 2;
  33435. }
  33436. }
  33437. // Result
  33438. var vertexData = new VertexData();
  33439. vertexData.positions = positions;
  33440. vertexData.indices = indices;
  33441. return vertexData;
  33442. };
  33443. /**
  33444. * Creates the VertexData of the Ground.
  33445. */
  33446. VertexData.CreateGround = function (options) {
  33447. var indices = [];
  33448. var positions = [];
  33449. var normals = [];
  33450. var uvs = [];
  33451. var row, col;
  33452. var width = options.width || 1;
  33453. var height = options.height || 1;
  33454. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33455. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33456. for (row = 0; row <= subdivisionsY; row++) {
  33457. for (col = 0; col <= subdivisionsX; col++) {
  33458. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33459. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33460. positions.push(position.x, position.y, position.z);
  33461. normals.push(normal.x, normal.y, normal.z);
  33462. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33463. }
  33464. }
  33465. for (row = 0; row < subdivisionsY; row++) {
  33466. for (col = 0; col < subdivisionsX; col++) {
  33467. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33468. indices.push(col + 1 + row * (subdivisionsX + 1));
  33469. indices.push(col + row * (subdivisionsX + 1));
  33470. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33471. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33472. indices.push(col + row * (subdivisionsX + 1));
  33473. }
  33474. }
  33475. // Result
  33476. var vertexData = new VertexData();
  33477. vertexData.indices = indices;
  33478. vertexData.positions = positions;
  33479. vertexData.normals = normals;
  33480. vertexData.uvs = uvs;
  33481. return vertexData;
  33482. };
  33483. /**
  33484. * Creates the VertexData of the TiledGround.
  33485. */
  33486. VertexData.CreateTiledGround = function (options) {
  33487. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33488. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33489. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33490. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33491. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33492. var precision = options.precision || { w: 1, h: 1 };
  33493. var indices = new Array();
  33494. var positions = new Array();
  33495. var normals = new Array();
  33496. var uvs = new Array();
  33497. var row, col, tileRow, tileCol;
  33498. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33499. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33500. precision.w = (precision.w < 1) ? 1 : precision.w;
  33501. precision.h = (precision.h < 1) ? 1 : precision.h;
  33502. var tileSize = {
  33503. 'w': (xmax - xmin) / subdivisions.w,
  33504. 'h': (zmax - zmin) / subdivisions.h
  33505. };
  33506. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33507. // Indices
  33508. var base = positions.length / 3;
  33509. var rowLength = precision.w + 1;
  33510. for (row = 0; row < precision.h; row++) {
  33511. for (col = 0; col < precision.w; col++) {
  33512. var square = [
  33513. base + col + row * rowLength,
  33514. base + (col + 1) + row * rowLength,
  33515. base + (col + 1) + (row + 1) * rowLength,
  33516. base + col + (row + 1) * rowLength
  33517. ];
  33518. indices.push(square[1]);
  33519. indices.push(square[2]);
  33520. indices.push(square[3]);
  33521. indices.push(square[0]);
  33522. indices.push(square[1]);
  33523. indices.push(square[3]);
  33524. }
  33525. }
  33526. // Position, normals and uvs
  33527. var position = BABYLON.Vector3.Zero();
  33528. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33529. for (row = 0; row <= precision.h; row++) {
  33530. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33531. for (col = 0; col <= precision.w; col++) {
  33532. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33533. position.y = 0;
  33534. positions.push(position.x, position.y, position.z);
  33535. normals.push(normal.x, normal.y, normal.z);
  33536. uvs.push(col / precision.w, row / precision.h);
  33537. }
  33538. }
  33539. }
  33540. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33541. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33542. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33543. }
  33544. }
  33545. // Result
  33546. var vertexData = new VertexData();
  33547. vertexData.indices = indices;
  33548. vertexData.positions = positions;
  33549. vertexData.normals = normals;
  33550. vertexData.uvs = uvs;
  33551. return vertexData;
  33552. };
  33553. /**
  33554. * Creates the VertexData of the Ground designed from a heightmap.
  33555. */
  33556. VertexData.CreateGroundFromHeightMap = function (options) {
  33557. var indices = [];
  33558. var positions = [];
  33559. var normals = [];
  33560. var uvs = [];
  33561. var row, col;
  33562. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33563. // Vertices
  33564. for (row = 0; row <= options.subdivisions; row++) {
  33565. for (col = 0; col <= options.subdivisions; col++) {
  33566. 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));
  33567. // Compute height
  33568. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33569. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33570. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33571. var r = options.buffer[pos] / 255.0;
  33572. var g = options.buffer[pos + 1] / 255.0;
  33573. var b = options.buffer[pos + 2] / 255.0;
  33574. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33575. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33576. // Add vertex
  33577. positions.push(position.x, position.y, position.z);
  33578. normals.push(0, 0, 0);
  33579. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33580. }
  33581. }
  33582. // Indices
  33583. for (row = 0; row < options.subdivisions; row++) {
  33584. for (col = 0; col < options.subdivisions; col++) {
  33585. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33586. indices.push(col + 1 + row * (options.subdivisions + 1));
  33587. indices.push(col + row * (options.subdivisions + 1));
  33588. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33589. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33590. indices.push(col + row * (options.subdivisions + 1));
  33591. }
  33592. }
  33593. // Normals
  33594. VertexData.ComputeNormals(positions, indices, normals);
  33595. // Result
  33596. var vertexData = new VertexData();
  33597. vertexData.indices = indices;
  33598. vertexData.positions = positions;
  33599. vertexData.normals = normals;
  33600. vertexData.uvs = uvs;
  33601. return vertexData;
  33602. };
  33603. /**
  33604. * Creates the VertexData of the Plane.
  33605. */
  33606. VertexData.CreatePlane = function (options) {
  33607. var indices = [];
  33608. var positions = [];
  33609. var normals = [];
  33610. var uvs = [];
  33611. var width = options.width || options.size || 1;
  33612. var height = options.height || options.size || 1;
  33613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33614. // Vertices
  33615. var halfWidth = width / 2.0;
  33616. var halfHeight = height / 2.0;
  33617. positions.push(-halfWidth, -halfHeight, 0);
  33618. normals.push(0, 0, -1.0);
  33619. uvs.push(0.0, 0.0);
  33620. positions.push(halfWidth, -halfHeight, 0);
  33621. normals.push(0, 0, -1.0);
  33622. uvs.push(1.0, 0.0);
  33623. positions.push(halfWidth, halfHeight, 0);
  33624. normals.push(0, 0, -1.0);
  33625. uvs.push(1.0, 1.0);
  33626. positions.push(-halfWidth, halfHeight, 0);
  33627. normals.push(0, 0, -1.0);
  33628. uvs.push(0.0, 1.0);
  33629. // Indices
  33630. indices.push(0);
  33631. indices.push(1);
  33632. indices.push(2);
  33633. indices.push(0);
  33634. indices.push(2);
  33635. indices.push(3);
  33636. // Sides
  33637. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33638. // Result
  33639. var vertexData = new VertexData();
  33640. vertexData.indices = indices;
  33641. vertexData.positions = positions;
  33642. vertexData.normals = normals;
  33643. vertexData.uvs = uvs;
  33644. return vertexData;
  33645. };
  33646. /**
  33647. * Creates the VertexData of the Disc or regular Polygon.
  33648. */
  33649. VertexData.CreateDisc = function (options) {
  33650. var positions = new Array();
  33651. var indices = new Array();
  33652. var normals = new Array();
  33653. var uvs = new Array();
  33654. var radius = options.radius || 0.5;
  33655. var tessellation = options.tessellation || 64;
  33656. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33658. // positions and uvs
  33659. positions.push(0, 0, 0); // disc center first
  33660. uvs.push(0.5, 0.5);
  33661. var theta = Math.PI * 2 * arc;
  33662. var step = theta / tessellation;
  33663. for (var a = 0; a < theta; a += step) {
  33664. var x = Math.cos(a);
  33665. var y = Math.sin(a);
  33666. var u = (x + 1) / 2;
  33667. var v = (1 - y) / 2;
  33668. positions.push(radius * x, radius * y, 0);
  33669. uvs.push(u, v);
  33670. }
  33671. if (arc === 1) {
  33672. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33673. uvs.push(uvs[2], uvs[3]);
  33674. }
  33675. //indices
  33676. var vertexNb = positions.length / 3;
  33677. for (var i = 1; i < vertexNb - 1; i++) {
  33678. indices.push(i + 1, 0, i);
  33679. }
  33680. // result
  33681. VertexData.ComputeNormals(positions, indices, normals);
  33682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33683. var vertexData = new VertexData();
  33684. vertexData.indices = indices;
  33685. vertexData.positions = positions;
  33686. vertexData.normals = normals;
  33687. vertexData.uvs = uvs;
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Re-creates the VertexData of the Polygon for sideOrientation.
  33692. */
  33693. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33694. var faceUV = fUV || new Array(3);
  33695. var faceColors = fColors;
  33696. var colors = [];
  33697. // default face colors and UV if undefined
  33698. for (var f = 0; f < 3; f++) {
  33699. if (faceUV[f] === undefined) {
  33700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33701. }
  33702. if (faceColors && faceColors[f] === undefined) {
  33703. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33704. }
  33705. }
  33706. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33707. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33708. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33709. var indices = polygon.getIndices();
  33710. // set face colours and textures
  33711. var idx = 0;
  33712. var face = 0;
  33713. for (var index = 0; index < normals.length; index += 3) {
  33714. //Edge Face no. 1
  33715. if (Math.abs(normals[index + 1]) < 0.001) {
  33716. face = 1;
  33717. }
  33718. //Top Face no. 0
  33719. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33720. face = 0;
  33721. }
  33722. //Bottom Face no. 2
  33723. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33724. face = 2;
  33725. }
  33726. idx = index / 3;
  33727. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33728. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33729. if (faceColors) {
  33730. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33731. }
  33732. }
  33733. // sides
  33734. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33735. // Result
  33736. var vertexData = new VertexData();
  33737. vertexData.indices = indices;
  33738. vertexData.positions = positions;
  33739. vertexData.normals = normals;
  33740. vertexData.uvs = uvs;
  33741. if (faceColors) {
  33742. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33743. vertexData.colors = totalColors;
  33744. }
  33745. return vertexData;
  33746. };
  33747. /**
  33748. * Creates the VertexData of the IcoSphere.
  33749. */
  33750. VertexData.CreateIcoSphere = function (options) {
  33751. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33752. var radius = options.radius || 1;
  33753. var flat = (options.flat === undefined) ? true : options.flat;
  33754. var subdivisions = options.subdivisions || 4;
  33755. var radiusX = options.radiusX || radius;
  33756. var radiusY = options.radiusY || radius;
  33757. var radiusZ = options.radiusZ || radius;
  33758. var t = (1 + Math.sqrt(5)) / 2;
  33759. // 12 vertex x,y,z
  33760. var ico_vertices = [
  33761. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33762. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33763. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33764. ];
  33765. // index of 3 vertex makes a face of icopshere
  33766. var ico_indices = [
  33767. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33768. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33769. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33770. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33771. ];
  33772. // vertex for uv have aliased position, not for UV
  33773. var vertices_unalias_id = [
  33774. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33775. // vertex alias
  33776. 0,
  33777. 2,
  33778. 3,
  33779. 3,
  33780. 3,
  33781. 4,
  33782. 7,
  33783. 8,
  33784. 9,
  33785. 9,
  33786. 10,
  33787. 11 // 23: B + 12
  33788. ];
  33789. // uv as integer step (not pixels !)
  33790. var ico_vertexuv = [
  33791. 5, 1, 3, 1, 6, 4, 0, 0,
  33792. 5, 3, 4, 2, 2, 2, 4, 0,
  33793. 2, 0, 1, 1, 6, 0, 6, 2,
  33794. // vertex alias (for same vertex on different faces)
  33795. 0, 4,
  33796. 3, 3,
  33797. 4, 4,
  33798. 3, 1,
  33799. 4, 2,
  33800. 4, 4,
  33801. 0, 2,
  33802. 1, 1,
  33803. 2, 2,
  33804. 3, 3,
  33805. 1, 3,
  33806. 2, 4 // 23: B + 12
  33807. ];
  33808. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33809. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33810. // First island of uv mapping
  33811. // v = 4h 3+ 2
  33812. // v = 3h 9+ 4
  33813. // v = 2h 9+ 5 B
  33814. // v = 1h 9 1 0
  33815. // v = 0h 3 8 7 A
  33816. // u = 0 1 2 3 4 5 6 *a
  33817. // Second island of uv mapping
  33818. // v = 4h 0+ B+ 4+
  33819. // v = 3h A+ 2+
  33820. // v = 2h 7+ 6 3+
  33821. // v = 1h 8+ 3+
  33822. // v = 0h
  33823. // u = 0 1 2 3 4 5 6 *a
  33824. // Face layout on texture UV mapping
  33825. // ============
  33826. // \ 4 /\ 16 / ======
  33827. // \ / \ / /\ 11 /
  33828. // \/ 7 \/ / \ /
  33829. // ======= / 10 \/
  33830. // /\ 17 /\ =======
  33831. // / \ / \ \ 15 /\
  33832. // / 8 \/ 12 \ \ / \
  33833. // ============ \/ 6 \
  33834. // \ 18 /\ ============
  33835. // \ / \ \ 5 /\ 0 /
  33836. // \/ 13 \ \ / \ /
  33837. // ======= \/ 1 \/
  33838. // =============
  33839. // /\ 19 /\ 2 /\
  33840. // / \ / \ / \
  33841. // / 14 \/ 9 \/ 3 \
  33842. // ===================
  33843. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33844. var ustep = 138 / 1024;
  33845. var vstep = 239 / 1024;
  33846. var uoffset = 60 / 1024;
  33847. var voffset = 26 / 1024;
  33848. // Second island should have margin, not to touch the first island
  33849. // avoid any borderline artefact in pixel rounding
  33850. var island_u_offset = -40 / 1024;
  33851. var island_v_offset = +20 / 1024;
  33852. // face is either island 0 or 1 :
  33853. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33854. var island = [
  33855. 0, 0, 0, 0, 1,
  33856. 0, 0, 1, 1, 0,
  33857. 0, 0, 1, 1, 0,
  33858. 0, 1, 1, 1, 0 // 15 - 19
  33859. ];
  33860. var indices = new Array();
  33861. var positions = new Array();
  33862. var normals = new Array();
  33863. var uvs = new Array();
  33864. var current_indice = 0;
  33865. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33866. var face_vertex_pos = new Array(3);
  33867. var face_vertex_uv = new Array(3);
  33868. var v012;
  33869. for (v012 = 0; v012 < 3; v012++) {
  33870. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33871. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33872. }
  33873. // create all with normals
  33874. for (var face = 0; face < 20; face++) {
  33875. // 3 vertex per face
  33876. for (v012 = 0; v012 < 3; v012++) {
  33877. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33878. var v_id = ico_indices[3 * face + v012];
  33879. // vertex have 3D position (x,y,z)
  33880. 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]);
  33881. // Normalize to get normal, then scale to radius
  33882. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33883. // uv Coordinates from vertex ID
  33884. 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);
  33885. }
  33886. // Subdivide the face (interpolate pos, norm, uv)
  33887. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33888. // - norm is linear interpolation of vertex corner normal
  33889. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33890. // - uv is linear interpolation
  33891. //
  33892. // Topology is as below for sub-divide by 2
  33893. // vertex shown as v0,v1,v2
  33894. // interp index is i1 to progress in range [v0,v1[
  33895. // interp index is i2 to progress in range [v0,v2[
  33896. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33897. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33898. //
  33899. //
  33900. // i2 v2
  33901. // ^ ^
  33902. // / / \
  33903. // / / \
  33904. // / / \
  33905. // / / (0,1) \
  33906. // / #---------\
  33907. // / / \ (0,0)'/ \
  33908. // / / \ / \
  33909. // / / \ / \
  33910. // / / (0,0) \ / (1,0) \
  33911. // / #---------#---------\
  33912. // v0 v1
  33913. //
  33914. // --------------------> i1
  33915. //
  33916. // interp of (i1,i2):
  33917. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33918. // along i1 : lerp(x0,x1, i1/(S-i2))
  33919. //
  33920. // centroid of triangle is needed to get help normal computation
  33921. // (c1,c2) are used for centroid location
  33922. var interp_vertex = function (i1, i2, c1, c2) {
  33923. // vertex is interpolated from
  33924. // - face_vertex_pos[0..2]
  33925. // - face_vertex_uv[0..2]
  33926. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33927. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33928. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33929. pos_interp.normalize();
  33930. var vertex_normal;
  33931. if (flat) {
  33932. // in flat mode, recalculate normal as face centroid normal
  33933. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33934. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33935. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33936. }
  33937. else {
  33938. // in smooth mode, recalculate normal from each single vertex position
  33939. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33940. }
  33941. // Vertex normal need correction due to X,Y,Z radius scaling
  33942. vertex_normal.x /= radiusX;
  33943. vertex_normal.y /= radiusY;
  33944. vertex_normal.z /= radiusZ;
  33945. vertex_normal.normalize();
  33946. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33947. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33948. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33949. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33950. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33951. uvs.push(uv_interp.x, uv_interp.y);
  33952. // push each vertex has member of a face
  33953. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33954. indices.push(current_indice);
  33955. current_indice++;
  33956. };
  33957. for (var i2 = 0; i2 < subdivisions; i2++) {
  33958. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33959. // face : (i1,i2) for /\ :
  33960. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33961. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33962. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33963. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33964. if (i1 + i2 + 1 < subdivisions) {
  33965. // face : (i1,i2)' for \/ :
  33966. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33967. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33968. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33969. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33970. }
  33971. }
  33972. }
  33973. }
  33974. // Sides
  33975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33976. // Result
  33977. var vertexData = new VertexData();
  33978. vertexData.indices = indices;
  33979. vertexData.positions = positions;
  33980. vertexData.normals = normals;
  33981. vertexData.uvs = uvs;
  33982. return vertexData;
  33983. };
  33984. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33985. /**
  33986. * Creates the VertexData of the Polyhedron.
  33987. */
  33988. VertexData.CreatePolyhedron = function (options) {
  33989. // provided polyhedron types :
  33990. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33991. // 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)
  33992. var polyhedra = [];
  33993. 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]] };
  33994. 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]] };
  33995. polyhedra[2] = {
  33996. 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]],
  33997. 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]]
  33998. };
  33999. polyhedra[3] = {
  34000. 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]],
  34001. 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]]
  34002. };
  34003. polyhedra[4] = {
  34004. 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]],
  34005. 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]]
  34006. };
  34007. 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]] };
  34008. 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]] };
  34009. 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]] };
  34010. 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]] };
  34011. 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]] };
  34012. 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]] };
  34013. 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]] };
  34014. 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]] };
  34015. 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]] };
  34016. polyhedra[14] = {
  34017. 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]],
  34018. 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]]
  34019. };
  34020. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34021. var size = options.size;
  34022. var sizeX = options.sizeX || size || 1;
  34023. var sizeY = options.sizeY || size || 1;
  34024. var sizeZ = options.sizeZ || size || 1;
  34025. var data = options.custom || polyhedra[type];
  34026. var nbfaces = data.face.length;
  34027. var faceUV = options.faceUV || new Array(nbfaces);
  34028. var faceColors = options.faceColors;
  34029. var flat = (options.flat === undefined) ? true : options.flat;
  34030. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34031. var positions = new Array();
  34032. var indices = new Array();
  34033. var normals = new Array();
  34034. var uvs = new Array();
  34035. var colors = new Array();
  34036. var index = 0;
  34037. var faceIdx = 0; // face cursor in the array "indexes"
  34038. var indexes = new Array();
  34039. var i = 0;
  34040. var f = 0;
  34041. var u, v, ang, x, y, tmp;
  34042. // default face colors and UV if undefined
  34043. if (flat) {
  34044. for (f = 0; f < nbfaces; f++) {
  34045. if (faceColors && faceColors[f] === undefined) {
  34046. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34047. }
  34048. if (faceUV && faceUV[f] === undefined) {
  34049. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34050. }
  34051. }
  34052. }
  34053. if (!flat) {
  34054. for (i = 0; i < data.vertex.length; i++) {
  34055. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34056. uvs.push(0, 0);
  34057. }
  34058. for (f = 0; f < nbfaces; f++) {
  34059. for (i = 0; i < data.face[f].length - 2; i++) {
  34060. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34061. }
  34062. }
  34063. }
  34064. else {
  34065. for (f = 0; f < nbfaces; f++) {
  34066. var fl = data.face[f].length; // number of vertices of the current face
  34067. ang = 2 * Math.PI / fl;
  34068. x = 0.5 * Math.tan(ang / 2);
  34069. y = 0.5;
  34070. // positions, uvs, colors
  34071. for (i = 0; i < fl; i++) {
  34072. // positions
  34073. 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);
  34074. indexes.push(index);
  34075. index++;
  34076. // uvs
  34077. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34078. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34079. uvs.push(u, v);
  34080. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34081. y = x * Math.sin(ang) + y * Math.cos(ang);
  34082. x = tmp;
  34083. // colors
  34084. if (faceColors) {
  34085. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34086. }
  34087. }
  34088. // indices from indexes
  34089. for (i = 0; i < fl - 2; i++) {
  34090. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34091. }
  34092. faceIdx += fl;
  34093. }
  34094. }
  34095. VertexData.ComputeNormals(positions, indices, normals);
  34096. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34097. var vertexData = new VertexData();
  34098. vertexData.positions = positions;
  34099. vertexData.indices = indices;
  34100. vertexData.normals = normals;
  34101. vertexData.uvs = uvs;
  34102. if (faceColors && flat) {
  34103. vertexData.colors = colors;
  34104. }
  34105. return vertexData;
  34106. };
  34107. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34108. /**
  34109. * Creates the VertexData of the Torus Knot.
  34110. */
  34111. VertexData.CreateTorusKnot = function (options) {
  34112. var indices = new Array();
  34113. var positions = new Array();
  34114. var normals = new Array();
  34115. var uvs = new Array();
  34116. var radius = options.radius || 2;
  34117. var tube = options.tube || 0.5;
  34118. var radialSegments = options.radialSegments || 32;
  34119. var tubularSegments = options.tubularSegments || 32;
  34120. var p = options.p || 2;
  34121. var q = options.q || 3;
  34122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34123. // Helper
  34124. var getPos = function (angle) {
  34125. var cu = Math.cos(angle);
  34126. var su = Math.sin(angle);
  34127. var quOverP = q / p * angle;
  34128. var cs = Math.cos(quOverP);
  34129. var tx = radius * (2 + cs) * 0.5 * cu;
  34130. var ty = radius * (2 + cs) * su * 0.5;
  34131. var tz = radius * Math.sin(quOverP) * 0.5;
  34132. return new BABYLON.Vector3(tx, ty, tz);
  34133. };
  34134. // Vertices
  34135. var i;
  34136. var j;
  34137. for (i = 0; i <= radialSegments; i++) {
  34138. var modI = i % radialSegments;
  34139. var u = modI / radialSegments * 2 * p * Math.PI;
  34140. var p1 = getPos(u);
  34141. var p2 = getPos(u + 0.01);
  34142. var tang = p2.subtract(p1);
  34143. var n = p2.add(p1);
  34144. var bitan = BABYLON.Vector3.Cross(tang, n);
  34145. n = BABYLON.Vector3.Cross(bitan, tang);
  34146. bitan.normalize();
  34147. n.normalize();
  34148. for (j = 0; j < tubularSegments; j++) {
  34149. var modJ = j % tubularSegments;
  34150. var v = modJ / tubularSegments * 2 * Math.PI;
  34151. var cx = -tube * Math.cos(v);
  34152. var cy = tube * Math.sin(v);
  34153. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34154. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34155. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34156. uvs.push(i / radialSegments);
  34157. uvs.push(j / tubularSegments);
  34158. }
  34159. }
  34160. for (i = 0; i < radialSegments; i++) {
  34161. for (j = 0; j < tubularSegments; j++) {
  34162. var jNext = (j + 1) % tubularSegments;
  34163. var a = i * tubularSegments + j;
  34164. var b = (i + 1) * tubularSegments + j;
  34165. var c = (i + 1) * tubularSegments + jNext;
  34166. var d = i * tubularSegments + jNext;
  34167. indices.push(d);
  34168. indices.push(b);
  34169. indices.push(a);
  34170. indices.push(d);
  34171. indices.push(c);
  34172. indices.push(b);
  34173. }
  34174. }
  34175. // Normals
  34176. VertexData.ComputeNormals(positions, indices, normals);
  34177. // Sides
  34178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34179. // Result
  34180. var vertexData = new VertexData();
  34181. vertexData.indices = indices;
  34182. vertexData.positions = positions;
  34183. vertexData.normals = normals;
  34184. vertexData.uvs = uvs;
  34185. return vertexData;
  34186. };
  34187. // Tools
  34188. /**
  34189. * @param {any} - positions (number[] or Float32Array)
  34190. * @param {any} - indices (number[] or Uint16Array)
  34191. * @param {any} - normals (number[] or Float32Array)
  34192. * options (optional) :
  34193. * facetPositions : optional array of facet positions (vector3)
  34194. * facetNormals : optional array of facet normals (vector3)
  34195. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34196. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34197. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34198. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34199. * bInfo : optional bounding info, required for facetPartitioning computation
  34200. * useRightHandedSystem: optional boolean to for right handed system computation
  34201. * depthSort : optional boolean to enable the facet depth sort computation
  34202. * distanceTo : optional Vector3 to compute the facet depth from this location
  34203. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34204. */
  34205. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34206. // temporary scalar variables
  34207. var index = 0; // facet index
  34208. var p1p2x = 0.0; // p1p2 vector x coordinate
  34209. var p1p2y = 0.0; // p1p2 vector y coordinate
  34210. var p1p2z = 0.0; // p1p2 vector z coordinate
  34211. var p3p2x = 0.0; // p3p2 vector x coordinate
  34212. var p3p2y = 0.0; // p3p2 vector y coordinate
  34213. var p3p2z = 0.0; // p3p2 vector z coordinate
  34214. var faceNormalx = 0.0; // facet normal x coordinate
  34215. var faceNormaly = 0.0; // facet normal y coordinate
  34216. var faceNormalz = 0.0; // facet normal z coordinate
  34217. var length = 0.0; // facet normal length before normalization
  34218. var v1x = 0; // vector1 x index in the positions array
  34219. var v1y = 0; // vector1 y index in the positions array
  34220. var v1z = 0; // vector1 z index in the positions array
  34221. var v2x = 0; // vector2 x index in the positions array
  34222. var v2y = 0; // vector2 y index in the positions array
  34223. var v2z = 0; // vector2 z index in the positions array
  34224. var v3x = 0; // vector3 x index in the positions array
  34225. var v3y = 0; // vector3 y index in the positions array
  34226. var v3z = 0; // vector3 z index in the positions array
  34227. var computeFacetNormals = false;
  34228. var computeFacetPositions = false;
  34229. var computeFacetPartitioning = false;
  34230. var computeDepthSort = false;
  34231. var faceNormalSign = 1;
  34232. var ratio = 0;
  34233. var distanceTo = null;
  34234. if (options) {
  34235. computeFacetNormals = (options.facetNormals) ? true : false;
  34236. computeFacetPositions = (options.facetPositions) ? true : false;
  34237. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34238. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34239. ratio = options.ratio || 0;
  34240. computeDepthSort = (options.depthSort) ? true : false;
  34241. distanceTo = (options.distanceTo);
  34242. if (computeDepthSort) {
  34243. if (distanceTo === undefined) {
  34244. distanceTo = BABYLON.Vector3.Zero();
  34245. }
  34246. var depthSortedFacets = options.depthSortedFacets;
  34247. }
  34248. }
  34249. // facetPartitioning reinit if needed
  34250. var xSubRatio = 0;
  34251. var ySubRatio = 0;
  34252. var zSubRatio = 0;
  34253. var subSq = 0;
  34254. if (computeFacetPartitioning && options && options.bbSize) {
  34255. var ox = 0; // X partitioning index for facet position
  34256. var oy = 0; // Y partinioning index for facet position
  34257. var oz = 0; // Z partinioning index for facet position
  34258. var b1x = 0; // X partitioning index for facet v1 vertex
  34259. var b1y = 0; // Y partitioning index for facet v1 vertex
  34260. var b1z = 0; // z partitioning index for facet v1 vertex
  34261. var b2x = 0; // X partitioning index for facet v2 vertex
  34262. var b2y = 0; // Y partitioning index for facet v2 vertex
  34263. var b2z = 0; // Z partitioning index for facet v2 vertex
  34264. var b3x = 0; // X partitioning index for facet v3 vertex
  34265. var b3y = 0; // Y partitioning index for facet v3 vertex
  34266. var b3z = 0; // Z partitioning index for facet v3 vertex
  34267. var block_idx_o = 0; // facet barycenter block index
  34268. var block_idx_v1 = 0; // v1 vertex block index
  34269. var block_idx_v2 = 0; // v2 vertex block index
  34270. var block_idx_v3 = 0; // v3 vertex block index
  34271. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34272. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34273. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34274. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34275. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34276. subSq = options.subDiv.max * options.subDiv.max;
  34277. options.facetPartitioning.length = 0;
  34278. }
  34279. // reset the normals
  34280. for (index = 0; index < positions.length; index++) {
  34281. normals[index] = 0.0;
  34282. }
  34283. // Loop : 1 indice triplet = 1 facet
  34284. var nbFaces = (indices.length / 3) | 0;
  34285. for (index = 0; index < nbFaces; index++) {
  34286. // get the indexes of the coordinates of each vertex of the facet
  34287. v1x = indices[index * 3] * 3;
  34288. v1y = v1x + 1;
  34289. v1z = v1x + 2;
  34290. v2x = indices[index * 3 + 1] * 3;
  34291. v2y = v2x + 1;
  34292. v2z = v2x + 2;
  34293. v3x = indices[index * 3 + 2] * 3;
  34294. v3y = v3x + 1;
  34295. v3z = v3x + 2;
  34296. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34297. p1p2y = positions[v1y] - positions[v2y];
  34298. p1p2z = positions[v1z] - positions[v2z];
  34299. p3p2x = positions[v3x] - positions[v2x];
  34300. p3p2y = positions[v3y] - positions[v2y];
  34301. p3p2z = positions[v3z] - positions[v2z];
  34302. // compute the face normal with the cross product
  34303. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34304. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34305. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34306. // normalize this normal and store it in the array facetData
  34307. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34308. length = (length === 0) ? 1.0 : length;
  34309. faceNormalx /= length;
  34310. faceNormaly /= length;
  34311. faceNormalz /= length;
  34312. if (computeFacetNormals && options) {
  34313. options.facetNormals[index].x = faceNormalx;
  34314. options.facetNormals[index].y = faceNormaly;
  34315. options.facetNormals[index].z = faceNormalz;
  34316. }
  34317. if (computeFacetPositions && options) {
  34318. // compute and the facet barycenter coordinates in the array facetPositions
  34319. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34320. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34321. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34322. }
  34323. if (computeFacetPartitioning && options) {
  34324. // store the facet indexes in arrays in the main facetPartitioning array :
  34325. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34326. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34327. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34328. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34329. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34330. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34331. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34332. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34333. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34334. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34335. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34336. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34337. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34338. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34339. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34340. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34341. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34342. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34343. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34344. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34345. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34346. // push each facet index in each block containing the vertex
  34347. options.facetPartitioning[block_idx_v1].push(index);
  34348. if (block_idx_v2 != block_idx_v1) {
  34349. options.facetPartitioning[block_idx_v2].push(index);
  34350. }
  34351. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34352. options.facetPartitioning[block_idx_v3].push(index);
  34353. }
  34354. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34355. options.facetPartitioning[block_idx_o].push(index);
  34356. }
  34357. }
  34358. if (computeDepthSort && options && options.facetPositions) {
  34359. var dsf = depthSortedFacets[index];
  34360. dsf.ind = index * 3;
  34361. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34362. }
  34363. // compute the normals anyway
  34364. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34365. normals[v1y] += faceNormaly;
  34366. normals[v1z] += faceNormalz;
  34367. normals[v2x] += faceNormalx;
  34368. normals[v2y] += faceNormaly;
  34369. normals[v2z] += faceNormalz;
  34370. normals[v3x] += faceNormalx;
  34371. normals[v3y] += faceNormaly;
  34372. normals[v3z] += faceNormalz;
  34373. }
  34374. // last normalization of each normal
  34375. for (index = 0; index < normals.length / 3; index++) {
  34376. faceNormalx = normals[index * 3];
  34377. faceNormaly = normals[index * 3 + 1];
  34378. faceNormalz = normals[index * 3 + 2];
  34379. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34380. length = (length === 0) ? 1.0 : length;
  34381. faceNormalx /= length;
  34382. faceNormaly /= length;
  34383. faceNormalz /= length;
  34384. normals[index * 3] = faceNormalx;
  34385. normals[index * 3 + 1] = faceNormaly;
  34386. normals[index * 3 + 2] = faceNormalz;
  34387. }
  34388. };
  34389. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34390. var li = indices.length;
  34391. var ln = normals.length;
  34392. var i;
  34393. var n;
  34394. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34395. switch (sideOrientation) {
  34396. case BABYLON.Mesh.FRONTSIDE:
  34397. // nothing changed
  34398. break;
  34399. case BABYLON.Mesh.BACKSIDE:
  34400. var tmp;
  34401. // indices
  34402. for (i = 0; i < li; i += 3) {
  34403. tmp = indices[i];
  34404. indices[i] = indices[i + 2];
  34405. indices[i + 2] = tmp;
  34406. }
  34407. // normals
  34408. for (n = 0; n < ln; n++) {
  34409. normals[n] = -normals[n];
  34410. }
  34411. break;
  34412. case BABYLON.Mesh.DOUBLESIDE:
  34413. // positions
  34414. var lp = positions.length;
  34415. var l = lp / 3;
  34416. for (var p = 0; p < lp; p++) {
  34417. positions[lp + p] = positions[p];
  34418. }
  34419. // indices
  34420. for (i = 0; i < li; i += 3) {
  34421. indices[i + li] = indices[i + 2] + l;
  34422. indices[i + 1 + li] = indices[i + 1] + l;
  34423. indices[i + 2 + li] = indices[i] + l;
  34424. }
  34425. // normals
  34426. for (n = 0; n < ln; n++) {
  34427. normals[ln + n] = -normals[n];
  34428. }
  34429. // uvs
  34430. var lu = uvs.length;
  34431. var u = 0;
  34432. for (u = 0; u < lu; u++) {
  34433. uvs[u + lu] = uvs[u];
  34434. }
  34435. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34436. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34437. u = 0;
  34438. for (i = 0; i < lu / 2; i++) {
  34439. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34440. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34441. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34442. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34443. u += 2;
  34444. }
  34445. break;
  34446. }
  34447. };
  34448. /**
  34449. * Creates a new VertexData from the imported parameters.
  34450. */
  34451. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34452. var vertexData = new VertexData();
  34453. // positions
  34454. var positions = parsedVertexData.positions;
  34455. if (positions) {
  34456. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34457. }
  34458. // normals
  34459. var normals = parsedVertexData.normals;
  34460. if (normals) {
  34461. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34462. }
  34463. // tangents
  34464. var tangents = parsedVertexData.tangents;
  34465. if (tangents) {
  34466. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34467. }
  34468. // uvs
  34469. var uvs = parsedVertexData.uvs;
  34470. if (uvs) {
  34471. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34472. }
  34473. // uv2s
  34474. var uv2s = parsedVertexData.uv2s;
  34475. if (uv2s) {
  34476. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34477. }
  34478. // uv3s
  34479. var uv3s = parsedVertexData.uv3s;
  34480. if (uv3s) {
  34481. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34482. }
  34483. // uv4s
  34484. var uv4s = parsedVertexData.uv4s;
  34485. if (uv4s) {
  34486. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34487. }
  34488. // uv5s
  34489. var uv5s = parsedVertexData.uv5s;
  34490. if (uv5s) {
  34491. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34492. }
  34493. // uv6s
  34494. var uv6s = parsedVertexData.uv6s;
  34495. if (uv6s) {
  34496. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34497. }
  34498. // colors
  34499. var colors = parsedVertexData.colors;
  34500. if (colors) {
  34501. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34502. }
  34503. // matricesIndices
  34504. var matricesIndices = parsedVertexData.matricesIndices;
  34505. if (matricesIndices) {
  34506. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34507. }
  34508. // matricesWeights
  34509. var matricesWeights = parsedVertexData.matricesWeights;
  34510. if (matricesWeights) {
  34511. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34512. }
  34513. // indices
  34514. var indices = parsedVertexData.indices;
  34515. if (indices) {
  34516. vertexData.indices = indices;
  34517. }
  34518. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34519. };
  34520. return VertexData;
  34521. }());
  34522. BABYLON.VertexData = VertexData;
  34523. })(BABYLON || (BABYLON = {}));
  34524. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34525. var BABYLON;
  34526. (function (BABYLON) {
  34527. /**
  34528. * Class used to store geometry data (vertex buffers + index buffer)
  34529. */
  34530. var Geometry = /** @class */ (function () {
  34531. /**
  34532. * Creates a new geometry
  34533. * @param id defines the unique ID
  34534. * @param scene defines the hosting scene
  34535. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34536. * @param updatable defines if geometry must be updatable (false by default)
  34537. * @param mesh defines the mesh that will be associated with the geometry
  34538. */
  34539. function Geometry(id, scene, vertexData, updatable, mesh) {
  34540. if (updatable === void 0) { updatable = false; }
  34541. if (mesh === void 0) { mesh = null; }
  34542. /**
  34543. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34544. */
  34545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34546. this._totalVertices = 0;
  34547. this._isDisposed = false;
  34548. this._indexBufferIsUpdatable = false;
  34549. this.id = id;
  34550. this._engine = scene.getEngine();
  34551. this._meshes = [];
  34552. this._scene = scene;
  34553. //Init vertex buffer cache
  34554. this._vertexBuffers = {};
  34555. this._indices = [];
  34556. this._updatable = updatable;
  34557. // vertexData
  34558. if (vertexData) {
  34559. this.setAllVerticesData(vertexData, updatable);
  34560. }
  34561. else {
  34562. this._totalVertices = 0;
  34563. this._indices = [];
  34564. }
  34565. if (this._engine.getCaps().vertexArrayObject) {
  34566. this._vertexArrayObjects = {};
  34567. }
  34568. // applyToMesh
  34569. if (mesh) {
  34570. if (mesh.getClassName() === "LinesMesh") {
  34571. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34572. this.updateExtend();
  34573. }
  34574. this.applyToMesh(mesh);
  34575. mesh.computeWorldMatrix(true);
  34576. }
  34577. }
  34578. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34579. /**
  34580. * 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
  34581. */
  34582. get: function () {
  34583. return this._boundingBias;
  34584. },
  34585. /**
  34586. * 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
  34587. */
  34588. set: function (value) {
  34589. if (this._boundingBias && this._boundingBias.equals(value)) {
  34590. return;
  34591. }
  34592. this._boundingBias = value.clone();
  34593. this.updateBoundingInfo(true, null);
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. /**
  34599. * Static function used to attach a new empty geometry to a mesh
  34600. * @param mesh defines the mesh to attach the geometry to
  34601. * @returns the new {BABYLON.Geometry}
  34602. */
  34603. Geometry.CreateGeometryForMesh = function (mesh) {
  34604. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34605. geometry.applyToMesh(mesh);
  34606. return geometry;
  34607. };
  34608. Object.defineProperty(Geometry.prototype, "extend", {
  34609. /**
  34610. * Gets the current extend of the geometry
  34611. */
  34612. get: function () {
  34613. return this._extend;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. /**
  34619. * Gets the hosting scene
  34620. * @returns the hosting {BABYLON.Scene}
  34621. */
  34622. Geometry.prototype.getScene = function () {
  34623. return this._scene;
  34624. };
  34625. /**
  34626. * Gets the hosting engine
  34627. * @returns the hosting {BABYLON.Engine}
  34628. */
  34629. Geometry.prototype.getEngine = function () {
  34630. return this._engine;
  34631. };
  34632. /**
  34633. * Defines if the geometry is ready to use
  34634. * @returns true if the geometry is ready to be used
  34635. */
  34636. Geometry.prototype.isReady = function () {
  34637. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34638. };
  34639. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34640. /**
  34641. * Gets a value indicating that the geometry should not be serialized
  34642. */
  34643. get: function () {
  34644. for (var index = 0; index < this._meshes.length; index++) {
  34645. if (!this._meshes[index].doNotSerialize) {
  34646. return false;
  34647. }
  34648. }
  34649. return true;
  34650. },
  34651. enumerable: true,
  34652. configurable: true
  34653. });
  34654. /** @ignore */
  34655. Geometry.prototype._rebuild = function () {
  34656. if (this._vertexArrayObjects) {
  34657. this._vertexArrayObjects = {};
  34658. }
  34659. // Index buffer
  34660. if (this._meshes.length !== 0 && this._indices) {
  34661. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34662. }
  34663. // Vertex buffers
  34664. for (var key in this._vertexBuffers) {
  34665. var vertexBuffer = this._vertexBuffers[key];
  34666. vertexBuffer._rebuild();
  34667. }
  34668. };
  34669. /**
  34670. * Affects all gemetry data in one call
  34671. * @param vertexData defines the geometry data
  34672. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34673. */
  34674. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34675. vertexData.applyToGeometry(this, updatable);
  34676. this.notifyUpdate();
  34677. };
  34678. /**
  34679. * Set specific vertex data
  34680. * @param kind defines the data kind (Position, normal, etc...)
  34681. * @param data defines the vertex data to use
  34682. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34683. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34684. */
  34685. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34686. if (updatable === void 0) { updatable = false; }
  34687. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34688. this.setVerticesBuffer(buffer);
  34689. };
  34690. /**
  34691. * Removes a specific vertex data
  34692. * @param kind defines the data kind (Position, normal, etc...)
  34693. */
  34694. Geometry.prototype.removeVerticesData = function (kind) {
  34695. if (this._vertexBuffers[kind]) {
  34696. this._vertexBuffers[kind].dispose();
  34697. delete this._vertexBuffers[kind];
  34698. }
  34699. };
  34700. /**
  34701. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34702. * @param buffer defines the vertex buffer to use
  34703. */
  34704. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34705. var kind = buffer.getKind();
  34706. if (this._vertexBuffers[kind]) {
  34707. this._vertexBuffers[kind].dispose();
  34708. }
  34709. this._vertexBuffers[kind] = buffer;
  34710. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34711. var data = buffer.getData();
  34712. var stride = buffer.getStrideSize();
  34713. this._totalVertices = data.length / stride;
  34714. this.updateExtend(data, stride);
  34715. this._resetPointsArrayCache();
  34716. var meshes = this._meshes;
  34717. var numOfMeshes = meshes.length;
  34718. for (var index = 0; index < numOfMeshes; index++) {
  34719. var mesh = meshes[index];
  34720. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34721. mesh._createGlobalSubMesh(false);
  34722. mesh.computeWorldMatrix(true);
  34723. }
  34724. }
  34725. this.notifyUpdate(kind);
  34726. if (this._vertexArrayObjects) {
  34727. this._disposeVertexArrayObjects();
  34728. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34729. }
  34730. };
  34731. /**
  34732. * Update a specific vertex buffer
  34733. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34734. * It will do nothing if the buffer is not updatable
  34735. * @param kind defines the data kind (Position, normal, etc...)
  34736. * @param data defines the data to use
  34737. * @param offset defines the offset in the target buffer where to store the data
  34738. */
  34739. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34740. var vertexBuffer = this.getVertexBuffer(kind);
  34741. if (!vertexBuffer) {
  34742. return;
  34743. }
  34744. vertexBuffer.updateDirectly(data, offset);
  34745. this.notifyUpdate(kind);
  34746. };
  34747. /**
  34748. * Update a specific vertex buffer
  34749. * This function will create a new buffer if the current one is not updatable
  34750. * @param kind defines the data kind (Position, normal, etc...)
  34751. * @param data defines the data to use
  34752. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34753. */
  34754. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34755. if (updateExtends === void 0) { updateExtends = false; }
  34756. var vertexBuffer = this.getVertexBuffer(kind);
  34757. if (!vertexBuffer) {
  34758. return;
  34759. }
  34760. vertexBuffer.update(data);
  34761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34762. var stride = vertexBuffer.getStrideSize();
  34763. this._totalVertices = data.length / stride;
  34764. this.updateBoundingInfo(updateExtends, data);
  34765. }
  34766. this.notifyUpdate(kind);
  34767. };
  34768. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34769. if (updateExtends) {
  34770. this.updateExtend(data);
  34771. }
  34772. var meshes = this._meshes;
  34773. var numOfMeshes = meshes.length;
  34774. this._resetPointsArrayCache();
  34775. for (var index = 0; index < numOfMeshes; index++) {
  34776. var mesh = meshes[index];
  34777. if (updateExtends) {
  34778. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34779. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34780. var subMesh = mesh.subMeshes[subIndex];
  34781. subMesh.refreshBoundingInfo();
  34782. }
  34783. }
  34784. }
  34785. };
  34786. /** @ignore */
  34787. Geometry.prototype._bind = function (effect, indexToBind) {
  34788. if (!effect) {
  34789. return;
  34790. }
  34791. if (indexToBind === undefined) {
  34792. indexToBind = this._indexBuffer;
  34793. }
  34794. var vbs = this.getVertexBuffers();
  34795. if (!vbs) {
  34796. return;
  34797. }
  34798. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34799. this._engine.bindBuffers(vbs, indexToBind, effect);
  34800. return;
  34801. }
  34802. // Using VAO
  34803. if (!this._vertexArrayObjects[effect.key]) {
  34804. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34805. }
  34806. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34807. };
  34808. /**
  34809. * Gets total number of vertices
  34810. * @returns the total number of vertices
  34811. */
  34812. Geometry.prototype.getTotalVertices = function () {
  34813. if (!this.isReady()) {
  34814. return 0;
  34815. }
  34816. return this._totalVertices;
  34817. };
  34818. /**
  34819. * Gets a specific vertex data attached to this geometry
  34820. * @param kind defines the data kind (Position, normal, etc...)
  34821. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34822. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34823. * @returns a float array containing vertex data
  34824. */
  34825. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34826. var vertexBuffer = this.getVertexBuffer(kind);
  34827. if (!vertexBuffer) {
  34828. return null;
  34829. }
  34830. var orig = vertexBuffer.getData();
  34831. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34832. return orig;
  34833. }
  34834. else {
  34835. var len = orig.length;
  34836. var copy = [];
  34837. for (var i = 0; i < len; i++) {
  34838. copy.push(orig[i]);
  34839. }
  34840. return copy;
  34841. }
  34842. };
  34843. /**
  34844. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34845. * @param kind defines the data kind (Position, normal, etc...)
  34846. * @returns true if the vertex buffer with the specified kind is updatable
  34847. */
  34848. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34849. var vb = this._vertexBuffers[kind];
  34850. if (!vb) {
  34851. return false;
  34852. }
  34853. return vb.isUpdatable();
  34854. };
  34855. /**
  34856. * Gets a specific vertex buffer
  34857. * @param kind defines the data kind (Position, normal, etc...)
  34858. * @returns a {BABYLON.VertexBuffer}
  34859. */
  34860. Geometry.prototype.getVertexBuffer = function (kind) {
  34861. if (!this.isReady()) {
  34862. return null;
  34863. }
  34864. return this._vertexBuffers[kind];
  34865. };
  34866. /**
  34867. * Returns all vertex buffers
  34868. * @return an object holding all vertex buffers indexed by kind
  34869. */
  34870. Geometry.prototype.getVertexBuffers = function () {
  34871. if (!this.isReady()) {
  34872. return null;
  34873. }
  34874. return this._vertexBuffers;
  34875. };
  34876. /**
  34877. * Gets a boolean indicating if specific vertex buffer is present
  34878. * @param kind defines the data kind (Position, normal, etc...)
  34879. * @returns true if data is present
  34880. */
  34881. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34882. if (!this._vertexBuffers) {
  34883. if (this._delayInfo) {
  34884. return this._delayInfo.indexOf(kind) !== -1;
  34885. }
  34886. return false;
  34887. }
  34888. return this._vertexBuffers[kind] !== undefined;
  34889. };
  34890. /**
  34891. * Gets a list of all attached data kinds (Position, normal, etc...)
  34892. * @returns a list of string containing all kinds
  34893. */
  34894. Geometry.prototype.getVerticesDataKinds = function () {
  34895. var result = [];
  34896. var kind;
  34897. if (!this._vertexBuffers && this._delayInfo) {
  34898. for (kind in this._delayInfo) {
  34899. result.push(kind);
  34900. }
  34901. }
  34902. else {
  34903. for (kind in this._vertexBuffers) {
  34904. result.push(kind);
  34905. }
  34906. }
  34907. return result;
  34908. };
  34909. /**
  34910. * Update index buffer
  34911. * @param indices defines the indices to store in the index buffer
  34912. * @param offset defines the offset in the target buffer where to store the data
  34913. */
  34914. Geometry.prototype.updateIndices = function (indices, offset) {
  34915. if (!this._indexBuffer) {
  34916. return;
  34917. }
  34918. if (!this._indexBufferIsUpdatable) {
  34919. this.setIndices(indices, null, true);
  34920. }
  34921. else {
  34922. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34923. }
  34924. };
  34925. /**
  34926. * Creates a new index buffer
  34927. * @param indices defines the indices to store in the index buffer
  34928. * @param totalVertices defines the total number of vertices (could be null)
  34929. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34930. */
  34931. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34932. if (totalVertices === void 0) { totalVertices = null; }
  34933. if (updatable === void 0) { updatable = false; }
  34934. if (this._indexBuffer) {
  34935. this._engine._releaseBuffer(this._indexBuffer);
  34936. }
  34937. this._disposeVertexArrayObjects();
  34938. this._indices = indices;
  34939. this._indexBufferIsUpdatable = updatable;
  34940. if (this._meshes.length !== 0 && this._indices) {
  34941. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34942. }
  34943. if (totalVertices != undefined) {
  34944. this._totalVertices = totalVertices;
  34945. }
  34946. var meshes = this._meshes;
  34947. var numOfMeshes = meshes.length;
  34948. for (var index = 0; index < numOfMeshes; index++) {
  34949. meshes[index]._createGlobalSubMesh(true);
  34950. }
  34951. this.notifyUpdate();
  34952. };
  34953. /**
  34954. * Return the total number of indices
  34955. * @returns the total number of indices
  34956. */
  34957. Geometry.prototype.getTotalIndices = function () {
  34958. if (!this.isReady()) {
  34959. return 0;
  34960. }
  34961. return this._indices.length;
  34962. };
  34963. /**
  34964. * Gets the index buffer array
  34965. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34966. * @returns the index buffer array
  34967. */
  34968. Geometry.prototype.getIndices = function (copyWhenShared) {
  34969. if (!this.isReady()) {
  34970. return null;
  34971. }
  34972. var orig = this._indices;
  34973. if (!copyWhenShared || this._meshes.length === 1) {
  34974. return orig;
  34975. }
  34976. else {
  34977. var len = orig.length;
  34978. var copy = [];
  34979. for (var i = 0; i < len; i++) {
  34980. copy.push(orig[i]);
  34981. }
  34982. return copy;
  34983. }
  34984. };
  34985. /**
  34986. * Gets the index buffer
  34987. * @return the index buffer
  34988. */
  34989. Geometry.prototype.getIndexBuffer = function () {
  34990. if (!this.isReady()) {
  34991. return null;
  34992. }
  34993. return this._indexBuffer;
  34994. };
  34995. /** @ignore */
  34996. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34997. if (effect === void 0) { effect = null; }
  34998. if (!effect || !this._vertexArrayObjects) {
  34999. return;
  35000. }
  35001. if (this._vertexArrayObjects[effect.key]) {
  35002. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35003. delete this._vertexArrayObjects[effect.key];
  35004. }
  35005. };
  35006. /**
  35007. * Release the associated resources for a specific mesh
  35008. * @param mesh defines the source mesh
  35009. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35010. */
  35011. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35012. var meshes = this._meshes;
  35013. var index = meshes.indexOf(mesh);
  35014. if (index === -1) {
  35015. return;
  35016. }
  35017. meshes.splice(index, 1);
  35018. mesh._geometry = null;
  35019. if (meshes.length === 0 && shouldDispose) {
  35020. this.dispose();
  35021. }
  35022. };
  35023. /**
  35024. * Apply current geometry to a given mesh
  35025. * @param mesh defines the mesh to apply geometry to
  35026. */
  35027. Geometry.prototype.applyToMesh = function (mesh) {
  35028. if (mesh._geometry === this) {
  35029. return;
  35030. }
  35031. var previousGeometry = mesh._geometry;
  35032. if (previousGeometry) {
  35033. previousGeometry.releaseForMesh(mesh);
  35034. }
  35035. var meshes = this._meshes;
  35036. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35037. mesh._geometry = this;
  35038. this._scene.pushGeometry(this);
  35039. meshes.push(mesh);
  35040. if (this.isReady()) {
  35041. this._applyToMesh(mesh);
  35042. }
  35043. else {
  35044. mesh._boundingInfo = this._boundingInfo;
  35045. }
  35046. };
  35047. Geometry.prototype.updateExtend = function (data, stride) {
  35048. if (data === void 0) { data = null; }
  35049. if (!data) {
  35050. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35051. }
  35052. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35053. };
  35054. Geometry.prototype._applyToMesh = function (mesh) {
  35055. var numOfMeshes = this._meshes.length;
  35056. // vertexBuffers
  35057. for (var kind in this._vertexBuffers) {
  35058. if (numOfMeshes === 1) {
  35059. this._vertexBuffers[kind].create();
  35060. }
  35061. var buffer = this._vertexBuffers[kind].getBuffer();
  35062. if (buffer)
  35063. buffer.references = numOfMeshes;
  35064. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35065. if (!this._extend) {
  35066. this.updateExtend(this._vertexBuffers[kind].getData());
  35067. }
  35068. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35069. mesh._createGlobalSubMesh(false);
  35070. //bounding info was just created again, world matrix should be applied again.
  35071. mesh._updateBoundingInfo();
  35072. }
  35073. }
  35074. // indexBuffer
  35075. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35076. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35077. }
  35078. if (this._indexBuffer) {
  35079. this._indexBuffer.references = numOfMeshes;
  35080. }
  35081. };
  35082. Geometry.prototype.notifyUpdate = function (kind) {
  35083. if (this.onGeometryUpdated) {
  35084. this.onGeometryUpdated(this, kind);
  35085. }
  35086. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35087. var mesh = _a[_i];
  35088. mesh._markSubMeshesAsAttributesDirty();
  35089. }
  35090. };
  35091. /**
  35092. * Load the geometry if it was flagged as delay loaded
  35093. * @param scene defines the hosting scene
  35094. * @param onLoaded defines a callback called when the geometry is loaded
  35095. */
  35096. Geometry.prototype.load = function (scene, onLoaded) {
  35097. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35098. return;
  35099. }
  35100. if (this.isReady()) {
  35101. if (onLoaded) {
  35102. onLoaded();
  35103. }
  35104. return;
  35105. }
  35106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35107. this._queueLoad(scene, onLoaded);
  35108. };
  35109. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35110. var _this = this;
  35111. if (!this.delayLoadingFile) {
  35112. return;
  35113. }
  35114. scene._addPendingData(this);
  35115. scene._loadFile(this.delayLoadingFile, function (data) {
  35116. if (!_this._delayLoadingFunction) {
  35117. return;
  35118. }
  35119. _this._delayLoadingFunction(JSON.parse(data), _this);
  35120. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35121. _this._delayInfo = [];
  35122. scene._removePendingData(_this);
  35123. var meshes = _this._meshes;
  35124. var numOfMeshes = meshes.length;
  35125. for (var index = 0; index < numOfMeshes; index++) {
  35126. _this._applyToMesh(meshes[index]);
  35127. }
  35128. if (onLoaded) {
  35129. onLoaded();
  35130. }
  35131. }, undefined, true);
  35132. };
  35133. /**
  35134. * Invert the geometry to move from a right handed system to a left handed one.
  35135. */
  35136. Geometry.prototype.toLeftHanded = function () {
  35137. // Flip faces
  35138. var tIndices = this.getIndices(false);
  35139. if (tIndices != null && tIndices.length > 0) {
  35140. for (var i = 0; i < tIndices.length; i += 3) {
  35141. var tTemp = tIndices[i + 0];
  35142. tIndices[i + 0] = tIndices[i + 2];
  35143. tIndices[i + 2] = tTemp;
  35144. }
  35145. this.setIndices(tIndices);
  35146. }
  35147. // Negate position.z
  35148. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35149. if (tPositions != null && tPositions.length > 0) {
  35150. for (var i = 0; i < tPositions.length; i += 3) {
  35151. tPositions[i + 2] = -tPositions[i + 2];
  35152. }
  35153. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35154. }
  35155. // Negate normal.z
  35156. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35157. if (tNormals != null && tNormals.length > 0) {
  35158. for (var i = 0; i < tNormals.length; i += 3) {
  35159. tNormals[i + 2] = -tNormals[i + 2];
  35160. }
  35161. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35162. }
  35163. };
  35164. // Cache
  35165. /** @ignore */
  35166. Geometry.prototype._resetPointsArrayCache = function () {
  35167. this._positions = null;
  35168. };
  35169. /** @ignore */
  35170. Geometry.prototype._generatePointsArray = function () {
  35171. if (this._positions)
  35172. return true;
  35173. this._positions = [];
  35174. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35175. if (!data) {
  35176. return false;
  35177. }
  35178. for (var index = 0; index < data.length; index += 3) {
  35179. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35180. }
  35181. return true;
  35182. };
  35183. /**
  35184. * Gets a value indicating if the geometry is disposed
  35185. * @returns true if the geometry was disposed
  35186. */
  35187. Geometry.prototype.isDisposed = function () {
  35188. return this._isDisposed;
  35189. };
  35190. Geometry.prototype._disposeVertexArrayObjects = function () {
  35191. if (this._vertexArrayObjects) {
  35192. for (var kind in this._vertexArrayObjects) {
  35193. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35194. }
  35195. this._vertexArrayObjects = {};
  35196. }
  35197. };
  35198. /**
  35199. * Free all associated resources
  35200. */
  35201. Geometry.prototype.dispose = function () {
  35202. var meshes = this._meshes;
  35203. var numOfMeshes = meshes.length;
  35204. var index;
  35205. for (index = 0; index < numOfMeshes; index++) {
  35206. this.releaseForMesh(meshes[index]);
  35207. }
  35208. this._meshes = [];
  35209. this._disposeVertexArrayObjects();
  35210. for (var kind in this._vertexBuffers) {
  35211. this._vertexBuffers[kind].dispose();
  35212. }
  35213. this._vertexBuffers = {};
  35214. this._totalVertices = 0;
  35215. if (this._indexBuffer) {
  35216. this._engine._releaseBuffer(this._indexBuffer);
  35217. }
  35218. this._indexBuffer = null;
  35219. this._indices = [];
  35220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35221. this.delayLoadingFile = null;
  35222. this._delayLoadingFunction = null;
  35223. this._delayInfo = [];
  35224. this._boundingInfo = null;
  35225. this._scene.removeGeometry(this);
  35226. this._isDisposed = true;
  35227. };
  35228. /**
  35229. * Clone the current geometry into a new geometry
  35230. * @param id defines the unique ID of the new geometry
  35231. * @returns a new geometry object
  35232. */
  35233. Geometry.prototype.copy = function (id) {
  35234. var vertexData = new BABYLON.VertexData();
  35235. vertexData.indices = [];
  35236. var indices = this.getIndices();
  35237. if (indices) {
  35238. for (var index = 0; index < indices.length; index++) {
  35239. vertexData.indices.push(indices[index]);
  35240. }
  35241. }
  35242. var updatable = false;
  35243. var stopChecking = false;
  35244. var kind;
  35245. for (kind in this._vertexBuffers) {
  35246. // using slice() to make a copy of the array and not just reference it
  35247. var data = this.getVerticesData(kind);
  35248. if (data instanceof Float32Array) {
  35249. vertexData.set(new Float32Array(data), kind);
  35250. }
  35251. else {
  35252. vertexData.set(data.slice(0), kind);
  35253. }
  35254. if (!stopChecking) {
  35255. var vb = this.getVertexBuffer(kind);
  35256. if (vb) {
  35257. updatable = vb.isUpdatable();
  35258. stopChecking = !updatable;
  35259. }
  35260. }
  35261. }
  35262. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35263. geometry.delayLoadState = this.delayLoadState;
  35264. geometry.delayLoadingFile = this.delayLoadingFile;
  35265. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35266. for (kind in this._delayInfo) {
  35267. geometry._delayInfo = geometry._delayInfo || [];
  35268. geometry._delayInfo.push(kind);
  35269. }
  35270. // Bounding info
  35271. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35272. return geometry;
  35273. };
  35274. /**
  35275. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35276. * @return a JSON representation of the current geometry data (without the vertices data)
  35277. */
  35278. Geometry.prototype.serialize = function () {
  35279. var serializationObject = {};
  35280. serializationObject.id = this.id;
  35281. serializationObject.updatable = this._updatable;
  35282. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35283. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35284. }
  35285. return serializationObject;
  35286. };
  35287. Geometry.prototype.toNumberArray = function (origin) {
  35288. if (Array.isArray(origin)) {
  35289. return origin;
  35290. }
  35291. else {
  35292. return Array.prototype.slice.call(origin);
  35293. }
  35294. };
  35295. /**
  35296. * Serialize all vertices data into a JSON oject
  35297. * @returns a JSON representation of the current geometry data
  35298. */
  35299. Geometry.prototype.serializeVerticeData = function () {
  35300. var serializationObject = this.serialize();
  35301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35302. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35303. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35304. serializationObject.positions._updatable = true;
  35305. }
  35306. }
  35307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35308. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35309. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35310. serializationObject.normals._updatable = true;
  35311. }
  35312. }
  35313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35314. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35315. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35316. serializationObject.tangets._updatable = true;
  35317. }
  35318. }
  35319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35320. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35321. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35322. serializationObject.uvs._updatable = true;
  35323. }
  35324. }
  35325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35326. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35327. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35328. serializationObject.uv2s._updatable = true;
  35329. }
  35330. }
  35331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35332. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35333. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35334. serializationObject.uv3s._updatable = true;
  35335. }
  35336. }
  35337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35338. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35340. serializationObject.uv4s._updatable = true;
  35341. }
  35342. }
  35343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35344. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35346. serializationObject.uv5s._updatable = true;
  35347. }
  35348. }
  35349. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35350. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35351. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35352. serializationObject.uv6s._updatable = true;
  35353. }
  35354. }
  35355. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35356. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35357. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35358. serializationObject.colors._updatable = true;
  35359. }
  35360. }
  35361. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35362. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35363. serializationObject.matricesIndices._isExpanded = true;
  35364. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35365. serializationObject.matricesIndices._updatable = true;
  35366. }
  35367. }
  35368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35369. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35371. serializationObject.matricesWeights._updatable = true;
  35372. }
  35373. }
  35374. serializationObject.indices = this.toNumberArray(this.getIndices());
  35375. return serializationObject;
  35376. };
  35377. // Statics
  35378. /**
  35379. * Extracts a clone of a mesh geometry
  35380. * @param mesh defines the source mesh
  35381. * @param id defines the unique ID of the new geometry object
  35382. * @returns the new geometry object
  35383. */
  35384. Geometry.ExtractFromMesh = function (mesh, id) {
  35385. var geometry = mesh._geometry;
  35386. if (!geometry) {
  35387. return null;
  35388. }
  35389. return geometry.copy(id);
  35390. };
  35391. /**
  35392. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35393. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35394. * Be aware Math.random() could cause collisions, but:
  35395. * "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"
  35396. * @returns a string containing a new GUID
  35397. */
  35398. Geometry.RandomId = function () {
  35399. return BABYLON.Tools.RandomId();
  35400. };
  35401. /** @ignore */
  35402. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35403. var scene = mesh.getScene();
  35404. // Geometry
  35405. var geometryId = parsedGeometry.geometryId;
  35406. if (geometryId) {
  35407. var geometry = scene.getGeometryByID(geometryId);
  35408. if (geometry) {
  35409. geometry.applyToMesh(mesh);
  35410. }
  35411. }
  35412. else if (parsedGeometry instanceof ArrayBuffer) {
  35413. var binaryInfo = mesh._binaryInfo;
  35414. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35415. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35416. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35417. }
  35418. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35419. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35420. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35421. }
  35422. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35423. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35424. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35425. }
  35426. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35427. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35428. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35429. }
  35430. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35431. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35433. }
  35434. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35435. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35436. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35437. }
  35438. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35439. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35440. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35441. }
  35442. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35443. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35444. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35445. }
  35446. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35447. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35448. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35449. }
  35450. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35451. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35452. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35453. }
  35454. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35455. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35457. }
  35458. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35459. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35461. }
  35462. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35463. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35464. mesh.setIndices(indicesData, null);
  35465. }
  35466. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35467. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35468. mesh.subMeshes = [];
  35469. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35470. var materialIndex = subMeshesData[(i * 5) + 0];
  35471. var verticesStart = subMeshesData[(i * 5) + 1];
  35472. var verticesCount = subMeshesData[(i * 5) + 2];
  35473. var indexStart = subMeshesData[(i * 5) + 3];
  35474. var indexCount = subMeshesData[(i * 5) + 4];
  35475. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35476. }
  35477. }
  35478. }
  35479. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35480. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35481. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35482. if (parsedGeometry.tangents) {
  35483. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35484. }
  35485. if (parsedGeometry.uvs) {
  35486. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35487. }
  35488. if (parsedGeometry.uvs2) {
  35489. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35490. }
  35491. if (parsedGeometry.uvs3) {
  35492. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35493. }
  35494. if (parsedGeometry.uvs4) {
  35495. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35496. }
  35497. if (parsedGeometry.uvs5) {
  35498. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35499. }
  35500. if (parsedGeometry.uvs6) {
  35501. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35502. }
  35503. if (parsedGeometry.colors) {
  35504. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35505. }
  35506. if (parsedGeometry.matricesIndices) {
  35507. if (!parsedGeometry.matricesIndices._isExpanded) {
  35508. var floatIndices = [];
  35509. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35510. var matricesIndex = parsedGeometry.matricesIndices[i];
  35511. floatIndices.push(matricesIndex & 0x000000FF);
  35512. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35513. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35514. floatIndices.push(matricesIndex >> 24);
  35515. }
  35516. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35517. }
  35518. else {
  35519. delete parsedGeometry.matricesIndices._isExpanded;
  35520. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35521. }
  35522. }
  35523. if (parsedGeometry.matricesIndicesExtra) {
  35524. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35525. var floatIndices = [];
  35526. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35527. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35528. floatIndices.push(matricesIndex & 0x000000FF);
  35529. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35530. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35531. floatIndices.push(matricesIndex >> 24);
  35532. }
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35534. }
  35535. else {
  35536. delete parsedGeometry.matricesIndices._isExpanded;
  35537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35538. }
  35539. }
  35540. if (parsedGeometry.matricesWeights) {
  35541. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35542. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35543. }
  35544. if (parsedGeometry.matricesWeightsExtra) {
  35545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35546. }
  35547. mesh.setIndices(parsedGeometry.indices, null);
  35548. }
  35549. // SubMeshes
  35550. if (parsedGeometry.subMeshes) {
  35551. mesh.subMeshes = [];
  35552. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35553. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35554. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35555. }
  35556. }
  35557. // Flat shading
  35558. if (mesh._shouldGenerateFlatShading) {
  35559. mesh.convertToFlatShadedMesh();
  35560. delete mesh._shouldGenerateFlatShading;
  35561. }
  35562. // Update
  35563. mesh.computeWorldMatrix(true);
  35564. // Octree
  35565. var sceneOctree = scene.selectionOctree;
  35566. if (sceneOctree !== undefined && sceneOctree !== null) {
  35567. sceneOctree.addMesh(mesh);
  35568. }
  35569. };
  35570. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35571. var epsilon = 1e-3;
  35572. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35573. return;
  35574. }
  35575. var noInfluenceBoneIndex = 0.0;
  35576. if (parsedGeometry.skeletonId > -1) {
  35577. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35578. if (!skeleton) {
  35579. return;
  35580. }
  35581. noInfluenceBoneIndex = skeleton.bones.length;
  35582. }
  35583. else {
  35584. return;
  35585. }
  35586. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35587. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35588. var matricesWeights = parsedGeometry.matricesWeights;
  35589. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35590. var influencers = parsedGeometry.numBoneInfluencer;
  35591. var size = matricesWeights.length;
  35592. for (var i = 0; i < size; i += 4) {
  35593. var weight = 0.0;
  35594. var firstZeroWeight = -1;
  35595. for (var j = 0; j < 4; j++) {
  35596. var w = matricesWeights[i + j];
  35597. weight += w;
  35598. if (w < epsilon && firstZeroWeight < 0) {
  35599. firstZeroWeight = j;
  35600. }
  35601. }
  35602. if (matricesWeightsExtra) {
  35603. for (var j = 0; j < 4; j++) {
  35604. var w = matricesWeightsExtra[i + j];
  35605. weight += w;
  35606. if (w < epsilon && firstZeroWeight < 0) {
  35607. firstZeroWeight = j + 4;
  35608. }
  35609. }
  35610. }
  35611. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35612. firstZeroWeight = influencers - 1;
  35613. }
  35614. if (weight > epsilon) {
  35615. var mweight = 1.0 / weight;
  35616. for (var j = 0; j < 4; j++) {
  35617. matricesWeights[i + j] *= mweight;
  35618. }
  35619. if (matricesWeightsExtra) {
  35620. for (var j = 0; j < 4; j++) {
  35621. matricesWeightsExtra[i + j] *= mweight;
  35622. }
  35623. }
  35624. }
  35625. else {
  35626. if (firstZeroWeight >= 4) {
  35627. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35628. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35629. }
  35630. else {
  35631. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35632. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35633. }
  35634. }
  35635. }
  35636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35637. if (parsedGeometry.matricesWeightsExtra) {
  35638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35639. }
  35640. };
  35641. /**
  35642. * Create a new geometry from persisted data (Using .babylon file format)
  35643. * @param parsedVertexData defines the persisted data
  35644. * @param scene defines the hosting scene
  35645. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35646. * @returns the new geometry object
  35647. */
  35648. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35649. if (scene.getGeometryByID(parsedVertexData.id)) {
  35650. return null; // null since geometry could be something else than a box...
  35651. }
  35652. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35653. if (BABYLON.Tags) {
  35654. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35655. }
  35656. if (parsedVertexData.delayLoadingFile) {
  35657. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35658. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35659. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35660. geometry._delayInfo = [];
  35661. if (parsedVertexData.hasUVs) {
  35662. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35663. }
  35664. if (parsedVertexData.hasUVs2) {
  35665. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35666. }
  35667. if (parsedVertexData.hasUVs3) {
  35668. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35669. }
  35670. if (parsedVertexData.hasUVs4) {
  35671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35672. }
  35673. if (parsedVertexData.hasUVs5) {
  35674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35675. }
  35676. if (parsedVertexData.hasUVs6) {
  35677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35678. }
  35679. if (parsedVertexData.hasColors) {
  35680. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35681. }
  35682. if (parsedVertexData.hasMatricesIndices) {
  35683. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35684. }
  35685. if (parsedVertexData.hasMatricesWeights) {
  35686. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35687. }
  35688. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35689. }
  35690. else {
  35691. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35692. }
  35693. scene.pushGeometry(geometry, true);
  35694. return geometry;
  35695. };
  35696. return Geometry;
  35697. }());
  35698. BABYLON.Geometry = Geometry;
  35699. // Primitives
  35700. /// Abstract class
  35701. /**
  35702. * Abstract class used to provide common services for all typed geometries
  35703. */
  35704. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35705. __extends(_PrimitiveGeometry, _super);
  35706. /**
  35707. * Creates a new typed geometry
  35708. * @param id defines the unique ID of the geometry
  35709. * @param scene defines the hosting scene
  35710. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35711. * @param mesh defines the hosting mesh (can be null)
  35712. */
  35713. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35714. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35715. if (mesh === void 0) { mesh = null; }
  35716. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35717. _this._canBeRegenerated = _canBeRegenerated;
  35718. _this._beingRegenerated = true;
  35719. _this.regenerate();
  35720. _this._beingRegenerated = false;
  35721. return _this;
  35722. }
  35723. /**
  35724. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35725. * @returns true if the geometry can be regenerated
  35726. */
  35727. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35728. return this._canBeRegenerated;
  35729. };
  35730. /**
  35731. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35732. */
  35733. _PrimitiveGeometry.prototype.regenerate = function () {
  35734. if (!this._canBeRegenerated) {
  35735. return;
  35736. }
  35737. this._beingRegenerated = true;
  35738. this.setAllVerticesData(this._regenerateVertexData(), false);
  35739. this._beingRegenerated = false;
  35740. };
  35741. /**
  35742. * Clone the geometry
  35743. * @param id defines the unique ID of the new geometry
  35744. * @returns the new geometry
  35745. */
  35746. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35747. return _super.prototype.copy.call(this, id);
  35748. };
  35749. // overrides
  35750. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35751. if (!this._beingRegenerated) {
  35752. return;
  35753. }
  35754. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35755. };
  35756. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35757. if (!this._beingRegenerated) {
  35758. return;
  35759. }
  35760. _super.prototype.setVerticesData.call(this, kind, data, false);
  35761. };
  35762. // to override
  35763. /** @ignore */
  35764. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35765. throw new Error("Abstract method");
  35766. };
  35767. _PrimitiveGeometry.prototype.copy = function (id) {
  35768. throw new Error("Must be overriden in sub-classes.");
  35769. };
  35770. _PrimitiveGeometry.prototype.serialize = function () {
  35771. var serializationObject = _super.prototype.serialize.call(this);
  35772. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35773. return serializationObject;
  35774. };
  35775. return _PrimitiveGeometry;
  35776. }(Geometry));
  35777. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35778. /**
  35779. * Creates a ribbon geometry
  35780. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35781. */
  35782. var RibbonGeometry = /** @class */ (function (_super) {
  35783. __extends(RibbonGeometry, _super);
  35784. /**
  35785. * Creates a ribbon geometry
  35786. * @param id defines the unique ID of the geometry
  35787. * @param scene defines the hosting scene
  35788. * @param pathArray defines the array of paths to use
  35789. * @param closeArray defines if the last path and the first path must be joined
  35790. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35791. * @param offset defines the offset between points
  35792. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35793. * @param mesh defines the hosting mesh (can be null)
  35794. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35795. */
  35796. function RibbonGeometry(id, scene,
  35797. /**
  35798. * Defines the array of paths to use
  35799. */
  35800. pathArray,
  35801. /**
  35802. * Defines if the last and first points of each path in your pathArray must be joined
  35803. */
  35804. closeArray,
  35805. /**
  35806. * Defines if the last and first points of each path in your pathArray must be joined
  35807. */
  35808. closePath,
  35809. /**
  35810. * Defines the offset between points
  35811. */
  35812. offset, canBeRegenerated, mesh,
  35813. /**
  35814. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35815. */
  35816. side) {
  35817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35819. _this.pathArray = pathArray;
  35820. _this.closeArray = closeArray;
  35821. _this.closePath = closePath;
  35822. _this.offset = offset;
  35823. _this.side = side;
  35824. return _this;
  35825. }
  35826. /** @ignore */
  35827. RibbonGeometry.prototype._regenerateVertexData = function () {
  35828. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35829. };
  35830. RibbonGeometry.prototype.copy = function (id) {
  35831. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35832. };
  35833. return RibbonGeometry;
  35834. }(_PrimitiveGeometry));
  35835. BABYLON.RibbonGeometry = RibbonGeometry;
  35836. /**
  35837. * Creates a box geometry
  35838. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35839. */
  35840. var BoxGeometry = /** @class */ (function (_super) {
  35841. __extends(BoxGeometry, _super);
  35842. /**
  35843. * Creates a box geometry
  35844. * @param id defines the unique ID of the geometry
  35845. * @param scene defines the hosting scene
  35846. * @param size defines the zise of the box (width, height and depth are the same)
  35847. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35848. * @param mesh defines the hosting mesh (can be null)
  35849. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. function BoxGeometry(id, scene,
  35852. /**
  35853. * Defines the zise of the box (width, height and depth are the same)
  35854. */
  35855. size, canBeRegenerated, mesh,
  35856. /**
  35857. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35858. */
  35859. side) {
  35860. if (mesh === void 0) { mesh = null; }
  35861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35862. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35863. _this.size = size;
  35864. _this.side = side;
  35865. return _this;
  35866. }
  35867. BoxGeometry.prototype._regenerateVertexData = function () {
  35868. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35869. };
  35870. BoxGeometry.prototype.copy = function (id) {
  35871. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35872. };
  35873. BoxGeometry.prototype.serialize = function () {
  35874. var serializationObject = _super.prototype.serialize.call(this);
  35875. serializationObject.size = this.size;
  35876. return serializationObject;
  35877. };
  35878. BoxGeometry.Parse = function (parsedBox, scene) {
  35879. if (scene.getGeometryByID(parsedBox.id)) {
  35880. return null; // null since geometry could be something else than a box...
  35881. }
  35882. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35883. if (BABYLON.Tags) {
  35884. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35885. }
  35886. scene.pushGeometry(box, true);
  35887. return box;
  35888. };
  35889. return BoxGeometry;
  35890. }(_PrimitiveGeometry));
  35891. BABYLON.BoxGeometry = BoxGeometry;
  35892. /**
  35893. * Creates a sphere geometry
  35894. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35895. */
  35896. var SphereGeometry = /** @class */ (function (_super) {
  35897. __extends(SphereGeometry, _super);
  35898. /**
  35899. * Create a new sphere geometry
  35900. * @param id defines the unique ID of the geometry
  35901. * @param scene defines the hosting scene
  35902. * @param segments defines the number of segments to use to create the sphere
  35903. * @param diameter defines the diameter of the sphere
  35904. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35905. * @param mesh defines the hosting mesh (can be null)
  35906. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35907. */
  35908. function SphereGeometry(id, scene,
  35909. /**
  35910. * Defines the number of segments to use to create the sphere
  35911. */
  35912. segments,
  35913. /**
  35914. * Defines the diameter of the sphere
  35915. */
  35916. diameter, canBeRegenerated, mesh,
  35917. /**
  35918. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35919. */
  35920. side) {
  35921. if (mesh === void 0) { mesh = null; }
  35922. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35923. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35924. _this.segments = segments;
  35925. _this.diameter = diameter;
  35926. _this.side = side;
  35927. return _this;
  35928. }
  35929. SphereGeometry.prototype._regenerateVertexData = function () {
  35930. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35931. };
  35932. SphereGeometry.prototype.copy = function (id) {
  35933. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35934. };
  35935. SphereGeometry.prototype.serialize = function () {
  35936. var serializationObject = _super.prototype.serialize.call(this);
  35937. serializationObject.segments = this.segments;
  35938. serializationObject.diameter = this.diameter;
  35939. return serializationObject;
  35940. };
  35941. SphereGeometry.Parse = function (parsedSphere, scene) {
  35942. if (scene.getGeometryByID(parsedSphere.id)) {
  35943. return null; // null since geometry could be something else than a sphere...
  35944. }
  35945. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35946. if (BABYLON.Tags) {
  35947. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35948. }
  35949. scene.pushGeometry(sphere, true);
  35950. return sphere;
  35951. };
  35952. return SphereGeometry;
  35953. }(_PrimitiveGeometry));
  35954. BABYLON.SphereGeometry = SphereGeometry;
  35955. /**
  35956. * Creates a disc geometry
  35957. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35958. */
  35959. var DiscGeometry = /** @class */ (function (_super) {
  35960. __extends(DiscGeometry, _super);
  35961. /**
  35962. * Creates a new disc geometry
  35963. * @param id defines the unique ID of the geometry
  35964. * @param scene defines the hosting scene
  35965. * @param radius defines the radius of the disc
  35966. * @param tessellation defines the tesselation factor to apply to the disc
  35967. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35968. * @param mesh defines the hosting mesh (can be null)
  35969. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35970. */
  35971. function DiscGeometry(id, scene,
  35972. /**
  35973. * Defines the radius of the disc
  35974. */
  35975. radius,
  35976. /**
  35977. * Defines the tesselation factor to apply to the disc
  35978. */
  35979. tessellation, canBeRegenerated, mesh,
  35980. /**
  35981. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35982. */
  35983. side) {
  35984. if (mesh === void 0) { mesh = null; }
  35985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35986. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35987. _this.radius = radius;
  35988. _this.tessellation = tessellation;
  35989. _this.side = side;
  35990. return _this;
  35991. }
  35992. DiscGeometry.prototype._regenerateVertexData = function () {
  35993. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35994. };
  35995. DiscGeometry.prototype.copy = function (id) {
  35996. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35997. };
  35998. return DiscGeometry;
  35999. }(_PrimitiveGeometry));
  36000. BABYLON.DiscGeometry = DiscGeometry;
  36001. /**
  36002. * Creates a new cylinder geometry
  36003. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36004. */
  36005. var CylinderGeometry = /** @class */ (function (_super) {
  36006. __extends(CylinderGeometry, _super);
  36007. /**
  36008. * Creates a new cylinder geometry
  36009. * @param id defines the unique ID of the geometry
  36010. * @param scene defines the hosting scene
  36011. * @param height defines the height of the cylinder
  36012. * @param diameterTop defines the diameter of the cylinder's top cap
  36013. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36014. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36015. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36016. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36017. * @param mesh defines the hosting mesh (can be null)
  36018. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36019. */
  36020. function CylinderGeometry(id, scene,
  36021. /**
  36022. * Defines the height of the cylinder
  36023. */
  36024. height,
  36025. /**
  36026. * Defines the diameter of the cylinder's top cap
  36027. */
  36028. diameterTop,
  36029. /**
  36030. * Defines the diameter of the cylinder's bottom cap
  36031. */
  36032. diameterBottom,
  36033. /**
  36034. * Defines the tessellation factor to apply to the cylinder
  36035. */
  36036. tessellation,
  36037. /**
  36038. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36039. */
  36040. subdivisions, canBeRegenerated, mesh,
  36041. /**
  36042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36043. */
  36044. side) {
  36045. if (subdivisions === void 0) { subdivisions = 1; }
  36046. if (mesh === void 0) { mesh = null; }
  36047. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36048. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36049. _this.height = height;
  36050. _this.diameterTop = diameterTop;
  36051. _this.diameterBottom = diameterBottom;
  36052. _this.tessellation = tessellation;
  36053. _this.subdivisions = subdivisions;
  36054. _this.side = side;
  36055. return _this;
  36056. }
  36057. CylinderGeometry.prototype._regenerateVertexData = function () {
  36058. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36059. };
  36060. CylinderGeometry.prototype.copy = function (id) {
  36061. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36062. };
  36063. CylinderGeometry.prototype.serialize = function () {
  36064. var serializationObject = _super.prototype.serialize.call(this);
  36065. serializationObject.height = this.height;
  36066. serializationObject.diameterTop = this.diameterTop;
  36067. serializationObject.diameterBottom = this.diameterBottom;
  36068. serializationObject.tessellation = this.tessellation;
  36069. return serializationObject;
  36070. };
  36071. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36072. if (scene.getGeometryByID(parsedCylinder.id)) {
  36073. return null; // null since geometry could be something else than a cylinder...
  36074. }
  36075. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36076. if (BABYLON.Tags) {
  36077. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36078. }
  36079. scene.pushGeometry(cylinder, true);
  36080. return cylinder;
  36081. };
  36082. return CylinderGeometry;
  36083. }(_PrimitiveGeometry));
  36084. BABYLON.CylinderGeometry = CylinderGeometry;
  36085. /**
  36086. * Creates a new torus geometry
  36087. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36088. */
  36089. var TorusGeometry = /** @class */ (function (_super) {
  36090. __extends(TorusGeometry, _super);
  36091. /**
  36092. * Creates a new torus geometry
  36093. * @param id defines the unique ID of the geometry
  36094. * @param scene defines the hosting scene
  36095. * @param diameter defines the diameter of the torus
  36096. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36097. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36098. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36099. * @param mesh defines the hosting mesh (can be null)
  36100. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36101. */
  36102. function TorusGeometry(id, scene,
  36103. /**
  36104. * Defines the diameter of the torus
  36105. */
  36106. diameter,
  36107. /**
  36108. * Defines the thickness of the torus (ie. internal diameter)
  36109. */
  36110. thickness,
  36111. /**
  36112. * Defines the tesselation factor to apply to the torus
  36113. */
  36114. tessellation, canBeRegenerated, mesh,
  36115. /**
  36116. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36117. */
  36118. side) {
  36119. if (mesh === void 0) { mesh = null; }
  36120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36122. _this.diameter = diameter;
  36123. _this.thickness = thickness;
  36124. _this.tessellation = tessellation;
  36125. _this.side = side;
  36126. return _this;
  36127. }
  36128. TorusGeometry.prototype._regenerateVertexData = function () {
  36129. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36130. };
  36131. TorusGeometry.prototype.copy = function (id) {
  36132. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36133. };
  36134. TorusGeometry.prototype.serialize = function () {
  36135. var serializationObject = _super.prototype.serialize.call(this);
  36136. serializationObject.diameter = this.diameter;
  36137. serializationObject.thickness = this.thickness;
  36138. serializationObject.tessellation = this.tessellation;
  36139. return serializationObject;
  36140. };
  36141. TorusGeometry.Parse = function (parsedTorus, scene) {
  36142. if (scene.getGeometryByID(parsedTorus.id)) {
  36143. return null; // null since geometry could be something else than a torus...
  36144. }
  36145. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36146. if (BABYLON.Tags) {
  36147. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36148. }
  36149. scene.pushGeometry(torus, true);
  36150. return torus;
  36151. };
  36152. return TorusGeometry;
  36153. }(_PrimitiveGeometry));
  36154. BABYLON.TorusGeometry = TorusGeometry;
  36155. /**
  36156. * Creates a new ground geometry
  36157. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36158. */
  36159. var GroundGeometry = /** @class */ (function (_super) {
  36160. __extends(GroundGeometry, _super);
  36161. /**
  36162. * Creates a new ground geometry
  36163. * @param id defines the unique ID of the geometry
  36164. * @param scene defines the hosting scene
  36165. * @param width defines the width of the ground
  36166. * @param height defines the height of the ground
  36167. * @param subdivisions defines the subdivisions to apply to the ground
  36168. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36169. * @param mesh defines the hosting mesh (can be null)
  36170. */
  36171. function GroundGeometry(id, scene,
  36172. /**
  36173. * Defines the width of the ground
  36174. */
  36175. width,
  36176. /**
  36177. * Defines the height of the ground
  36178. */
  36179. height,
  36180. /**
  36181. * Defines the subdivisions to apply to the ground
  36182. */
  36183. subdivisions, canBeRegenerated, mesh) {
  36184. if (mesh === void 0) { mesh = null; }
  36185. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36186. _this.width = width;
  36187. _this.height = height;
  36188. _this.subdivisions = subdivisions;
  36189. return _this;
  36190. }
  36191. GroundGeometry.prototype._regenerateVertexData = function () {
  36192. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36193. };
  36194. GroundGeometry.prototype.copy = function (id) {
  36195. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36196. };
  36197. GroundGeometry.prototype.serialize = function () {
  36198. var serializationObject = _super.prototype.serialize.call(this);
  36199. serializationObject.width = this.width;
  36200. serializationObject.height = this.height;
  36201. serializationObject.subdivisions = this.subdivisions;
  36202. return serializationObject;
  36203. };
  36204. GroundGeometry.Parse = function (parsedGround, scene) {
  36205. if (scene.getGeometryByID(parsedGround.id)) {
  36206. return null; // null since geometry could be something else than a ground...
  36207. }
  36208. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36209. if (BABYLON.Tags) {
  36210. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36211. }
  36212. scene.pushGeometry(ground, true);
  36213. return ground;
  36214. };
  36215. return GroundGeometry;
  36216. }(_PrimitiveGeometry));
  36217. BABYLON.GroundGeometry = GroundGeometry;
  36218. /**
  36219. * Creates a tiled ground geometry
  36220. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36221. */
  36222. var TiledGroundGeometry = /** @class */ (function (_super) {
  36223. __extends(TiledGroundGeometry, _super);
  36224. /**
  36225. * Creates a tiled ground geometry
  36226. * @param id defines the unique ID of the geometry
  36227. * @param scene defines the hosting scene
  36228. * @param xmin defines the minimum value on X axis
  36229. * @param zmin defines the minimum value on Z axis
  36230. * @param xmax defines the maximum value on X axis
  36231. * @param zmax defines the maximum value on Z axis
  36232. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36233. * @param precision defines the precision to use when computing the tiles
  36234. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36235. * @param mesh defines the hosting mesh (can be null)
  36236. */
  36237. function TiledGroundGeometry(id, scene,
  36238. /**
  36239. * Defines the minimum value on X axis
  36240. */
  36241. xmin,
  36242. /**
  36243. * Defines the minimum value on Z axis
  36244. */
  36245. zmin,
  36246. /**
  36247. * Defines the maximum value on X axis
  36248. */
  36249. xmax,
  36250. /**
  36251. * Defines the maximum value on Z axis
  36252. */
  36253. zmax,
  36254. /**
  36255. * Defines the subdivisions to apply to the ground
  36256. */
  36257. subdivisions,
  36258. /**
  36259. * Defines the precision to use when computing the tiles
  36260. */
  36261. precision, canBeRegenerated, mesh) {
  36262. if (mesh === void 0) { mesh = null; }
  36263. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36264. _this.xmin = xmin;
  36265. _this.zmin = zmin;
  36266. _this.xmax = xmax;
  36267. _this.zmax = zmax;
  36268. _this.subdivisions = subdivisions;
  36269. _this.precision = precision;
  36270. return _this;
  36271. }
  36272. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36273. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36274. };
  36275. TiledGroundGeometry.prototype.copy = function (id) {
  36276. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36277. };
  36278. return TiledGroundGeometry;
  36279. }(_PrimitiveGeometry));
  36280. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36281. /**
  36282. * Creates a plane geometry
  36283. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36284. */
  36285. var PlaneGeometry = /** @class */ (function (_super) {
  36286. __extends(PlaneGeometry, _super);
  36287. /**
  36288. * Creates a plane geometry
  36289. * @param id defines the unique ID of the geometry
  36290. * @param scene defines the hosting scene
  36291. * @param size defines the size of the plane (width === height)
  36292. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36293. * @param mesh defines the hosting mesh (can be null)
  36294. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36295. */
  36296. function PlaneGeometry(id, scene,
  36297. /**
  36298. * Defines the size of the plane (width === height)
  36299. */
  36300. size, canBeRegenerated, mesh,
  36301. /**
  36302. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36303. */
  36304. side) {
  36305. if (mesh === void 0) { mesh = null; }
  36306. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36308. _this.size = size;
  36309. _this.side = side;
  36310. return _this;
  36311. }
  36312. PlaneGeometry.prototype._regenerateVertexData = function () {
  36313. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36314. };
  36315. PlaneGeometry.prototype.copy = function (id) {
  36316. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36317. };
  36318. PlaneGeometry.prototype.serialize = function () {
  36319. var serializationObject = _super.prototype.serialize.call(this);
  36320. serializationObject.size = this.size;
  36321. return serializationObject;
  36322. };
  36323. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36324. if (scene.getGeometryByID(parsedPlane.id)) {
  36325. return null; // null since geometry could be something else than a ground...
  36326. }
  36327. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36328. if (BABYLON.Tags) {
  36329. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36330. }
  36331. scene.pushGeometry(plane, true);
  36332. return plane;
  36333. };
  36334. return PlaneGeometry;
  36335. }(_PrimitiveGeometry));
  36336. BABYLON.PlaneGeometry = PlaneGeometry;
  36337. /**
  36338. * Creates a torus knot geometry
  36339. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36340. */
  36341. var TorusKnotGeometry = /** @class */ (function (_super) {
  36342. __extends(TorusKnotGeometry, _super);
  36343. /**
  36344. * Creates a torus knot geometry
  36345. * @param id defines the unique ID of the geometry
  36346. * @param scene defines the hosting scene
  36347. * @param radius defines the radius of the torus knot
  36348. * @param tube defines the thickness of the torus knot tube
  36349. * @param radialSegments defines the number of radial segments
  36350. * @param tubularSegments defines the number of tubular segments
  36351. * @param p defines the first number of windings
  36352. * @param q defines the second number of windings
  36353. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36354. * @param mesh defines the hosting mesh (can be null)
  36355. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36356. */
  36357. function TorusKnotGeometry(id, scene,
  36358. /**
  36359. * Defines the radius of the torus knot
  36360. */
  36361. radius,
  36362. /**
  36363. * Defines the thickness of the torus knot tube
  36364. */
  36365. tube,
  36366. /**
  36367. * Defines the number of radial segments
  36368. */
  36369. radialSegments,
  36370. /**
  36371. * Defines the number of tubular segments
  36372. */
  36373. tubularSegments,
  36374. /**
  36375. * Defines the first number of windings
  36376. */
  36377. p,
  36378. /**
  36379. * Defines the second number of windings
  36380. */
  36381. q, canBeRegenerated, mesh,
  36382. /**
  36383. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36384. */
  36385. side) {
  36386. if (mesh === void 0) { mesh = null; }
  36387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36389. _this.radius = radius;
  36390. _this.tube = tube;
  36391. _this.radialSegments = radialSegments;
  36392. _this.tubularSegments = tubularSegments;
  36393. _this.p = p;
  36394. _this.q = q;
  36395. _this.side = side;
  36396. return _this;
  36397. }
  36398. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36399. 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 });
  36400. };
  36401. TorusKnotGeometry.prototype.copy = function (id) {
  36402. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36403. };
  36404. TorusKnotGeometry.prototype.serialize = function () {
  36405. var serializationObject = _super.prototype.serialize.call(this);
  36406. serializationObject.radius = this.radius;
  36407. serializationObject.tube = this.tube;
  36408. serializationObject.radialSegments = this.radialSegments;
  36409. serializationObject.tubularSegments = this.tubularSegments;
  36410. serializationObject.p = this.p;
  36411. serializationObject.q = this.q;
  36412. return serializationObject;
  36413. };
  36414. ;
  36415. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36416. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36417. return null; // null since geometry could be something else than a ground...
  36418. }
  36419. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36420. if (BABYLON.Tags) {
  36421. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36422. }
  36423. scene.pushGeometry(torusKnot, true);
  36424. return torusKnot;
  36425. };
  36426. return TorusKnotGeometry;
  36427. }(_PrimitiveGeometry));
  36428. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36429. //}
  36430. })(BABYLON || (BABYLON = {}));
  36431. //# sourceMappingURL=babylon.geometry.js.map
  36432. var BABYLON;
  36433. (function (BABYLON) {
  36434. /**
  36435. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36436. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36437. */
  36438. var PostProcessManager = /** @class */ (function () {
  36439. /**
  36440. * Creates a new instance of @see PostProcess
  36441. * @param scene The scene that the post process is associated with.
  36442. */
  36443. function PostProcessManager(scene) {
  36444. this._vertexBuffers = {};
  36445. this._scene = scene;
  36446. }
  36447. PostProcessManager.prototype._prepareBuffers = function () {
  36448. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36449. return;
  36450. }
  36451. // VBO
  36452. var vertices = [];
  36453. vertices.push(1, 1);
  36454. vertices.push(-1, 1);
  36455. vertices.push(-1, -1);
  36456. vertices.push(1, -1);
  36457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36458. this._buildIndexBuffer();
  36459. };
  36460. PostProcessManager.prototype._buildIndexBuffer = function () {
  36461. // Indices
  36462. var indices = [];
  36463. indices.push(0);
  36464. indices.push(1);
  36465. indices.push(2);
  36466. indices.push(0);
  36467. indices.push(2);
  36468. indices.push(3);
  36469. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36470. };
  36471. /**
  36472. * Rebuilds the vertex buffers of the manager.
  36473. */
  36474. PostProcessManager.prototype._rebuild = function () {
  36475. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36476. if (!vb) {
  36477. return;
  36478. }
  36479. vb._rebuild();
  36480. this._buildIndexBuffer();
  36481. };
  36482. // Methods
  36483. /**
  36484. * Prepares a frame to be run through a post process.
  36485. * @param sourceTexture The input texture to the post procesess. (default: null)
  36486. * @param postProcesses An array of post processes to be run. (default: null)
  36487. * @returns True if the post processes were able to be run.
  36488. */
  36489. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36490. if (sourceTexture === void 0) { sourceTexture = null; }
  36491. if (postProcesses === void 0) { postProcesses = null; }
  36492. var camera = this._scene.activeCamera;
  36493. if (!camera) {
  36494. return false;
  36495. }
  36496. var postProcesses = postProcesses || camera._postProcesses;
  36497. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36498. return false;
  36499. }
  36500. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36501. return true;
  36502. };
  36503. /**
  36504. * Manually render a set of post processes to a texture.
  36505. * @param postProcesses An array of post processes to be run.
  36506. * @param targetTexture The target texture to render to.
  36507. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36508. */
  36509. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36510. if (targetTexture === void 0) { targetTexture = null; }
  36511. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36512. var engine = this._scene.getEngine();
  36513. for (var index = 0; index < postProcesses.length; index++) {
  36514. if (index < postProcesses.length - 1) {
  36515. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36516. }
  36517. else {
  36518. if (targetTexture) {
  36519. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36520. }
  36521. else {
  36522. engine.restoreDefaultFramebuffer();
  36523. }
  36524. }
  36525. var pp = postProcesses[index];
  36526. var effect = pp.apply();
  36527. if (effect) {
  36528. pp.onBeforeRenderObservable.notifyObservers(effect);
  36529. // VBOs
  36530. this._prepareBuffers();
  36531. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36532. // Draw order
  36533. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36534. pp.onAfterRenderObservable.notifyObservers(effect);
  36535. }
  36536. }
  36537. // Restore depth buffer
  36538. engine.setDepthBuffer(true);
  36539. engine.setDepthWrite(true);
  36540. };
  36541. /**
  36542. * Finalize the result of the output of the postprocesses.
  36543. * @param doNotPresent If true the result will not be displayed to the screen.
  36544. * @param targetTexture The target texture to render to.
  36545. * @param faceIndex The index of the face to bind the target texture to.
  36546. * @param postProcesses The array of post processes to render.
  36547. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36548. */
  36549. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36550. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36551. var camera = this._scene.activeCamera;
  36552. if (!camera) {
  36553. return;
  36554. }
  36555. postProcesses = postProcesses || camera._postProcesses;
  36556. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36557. return;
  36558. }
  36559. var engine = this._scene.getEngine();
  36560. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36561. if (index < len - 1) {
  36562. postProcesses[index + 1].activate(camera, targetTexture);
  36563. }
  36564. else {
  36565. if (targetTexture) {
  36566. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36567. }
  36568. else {
  36569. engine.restoreDefaultFramebuffer();
  36570. }
  36571. }
  36572. if (doNotPresent) {
  36573. break;
  36574. }
  36575. var pp = postProcesses[index];
  36576. var effect = pp.apply();
  36577. if (effect) {
  36578. pp.onBeforeRenderObservable.notifyObservers(effect);
  36579. // VBOs
  36580. this._prepareBuffers();
  36581. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36582. // Draw order
  36583. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36584. pp.onAfterRenderObservable.notifyObservers(effect);
  36585. }
  36586. }
  36587. // Restore states
  36588. engine.setDepthBuffer(true);
  36589. engine.setDepthWrite(true);
  36590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36591. };
  36592. /**
  36593. * Disposes of the post process manager.
  36594. */
  36595. PostProcessManager.prototype.dispose = function () {
  36596. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36597. if (buffer) {
  36598. buffer.dispose();
  36599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36600. }
  36601. if (this._indexBuffer) {
  36602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36603. this._indexBuffer = null;
  36604. }
  36605. };
  36606. return PostProcessManager;
  36607. }());
  36608. BABYLON.PostProcessManager = PostProcessManager;
  36609. })(BABYLON || (BABYLON = {}));
  36610. //# sourceMappingURL=babylon.postProcessManager.js.map
  36611. var BABYLON;
  36612. (function (BABYLON) {
  36613. /**
  36614. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36615. */
  36616. var PerformanceMonitor = /** @class */ (function () {
  36617. /**
  36618. * constructor
  36619. * @param frameSampleSize The number of samples required to saturate the sliding window
  36620. */
  36621. function PerformanceMonitor(frameSampleSize) {
  36622. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36623. this._enabled = true;
  36624. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36625. }
  36626. /**
  36627. * Samples current frame
  36628. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36629. */
  36630. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36631. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36632. if (!this._enabled)
  36633. return;
  36634. if (this._lastFrameTimeMs != null) {
  36635. var dt = timeMs - this._lastFrameTimeMs;
  36636. this._rollingFrameTime.add(dt);
  36637. }
  36638. this._lastFrameTimeMs = timeMs;
  36639. };
  36640. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36641. /**
  36642. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36643. * @return Average frame time in milliseconds
  36644. */
  36645. get: function () {
  36646. return this._rollingFrameTime.average;
  36647. },
  36648. enumerable: true,
  36649. configurable: true
  36650. });
  36651. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36652. /**
  36653. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36654. * @return Frame time variance in milliseconds squared
  36655. */
  36656. get: function () {
  36657. return this._rollingFrameTime.variance;
  36658. },
  36659. enumerable: true,
  36660. configurable: true
  36661. });
  36662. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36663. /**
  36664. * Returns the frame time of the most recent frame
  36665. * @return Frame time in milliseconds
  36666. */
  36667. get: function () {
  36668. return this._rollingFrameTime.history(0);
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36674. /**
  36675. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36676. * @return Framerate in frames per second
  36677. */
  36678. get: function () {
  36679. return 1000.0 / this._rollingFrameTime.average;
  36680. },
  36681. enumerable: true,
  36682. configurable: true
  36683. });
  36684. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36685. /**
  36686. * Returns the average framerate in frames per second using the most recent frame time
  36687. * @return Framerate in frames per second
  36688. */
  36689. get: function () {
  36690. var history = this._rollingFrameTime.history(0);
  36691. if (history === 0) {
  36692. return 0;
  36693. }
  36694. return 1000.0 / history;
  36695. },
  36696. enumerable: true,
  36697. configurable: true
  36698. });
  36699. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36700. /**
  36701. * Returns true if enough samples have been taken to completely fill the sliding window
  36702. * @return true if saturated
  36703. */
  36704. get: function () {
  36705. return this._rollingFrameTime.isSaturated();
  36706. },
  36707. enumerable: true,
  36708. configurable: true
  36709. });
  36710. /**
  36711. * Enables contributions to the sliding window sample set
  36712. */
  36713. PerformanceMonitor.prototype.enable = function () {
  36714. this._enabled = true;
  36715. };
  36716. /**
  36717. * Disables contributions to the sliding window sample set
  36718. * Samples will not be interpolated over the disabled period
  36719. */
  36720. PerformanceMonitor.prototype.disable = function () {
  36721. this._enabled = false;
  36722. //clear last sample to avoid interpolating over the disabled period when next enabled
  36723. this._lastFrameTimeMs = null;
  36724. };
  36725. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36726. /**
  36727. * Returns true if sampling is enabled
  36728. * @return true if enabled
  36729. */
  36730. get: function () {
  36731. return this._enabled;
  36732. },
  36733. enumerable: true,
  36734. configurable: true
  36735. });
  36736. /**
  36737. * Resets performance monitor
  36738. */
  36739. PerformanceMonitor.prototype.reset = function () {
  36740. //clear last sample to avoid interpolating over the disabled period when next enabled
  36741. this._lastFrameTimeMs = null;
  36742. //wipe record
  36743. this._rollingFrameTime.reset();
  36744. };
  36745. return PerformanceMonitor;
  36746. }());
  36747. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36748. /**
  36749. * RollingAverage
  36750. *
  36751. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36752. */
  36753. var RollingAverage = /** @class */ (function () {
  36754. /**
  36755. * constructor
  36756. * @param length The number of samples required to saturate the sliding window
  36757. */
  36758. function RollingAverage(length) {
  36759. this._samples = new Array(length);
  36760. this.reset();
  36761. }
  36762. /**
  36763. * Adds a sample to the sample set
  36764. * @param v The sample value
  36765. */
  36766. RollingAverage.prototype.add = function (v) {
  36767. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36768. var delta;
  36769. //we need to check if we've already wrapped round
  36770. if (this.isSaturated()) {
  36771. //remove bottom of stack from mean
  36772. var bottomValue = this._samples[this._pos];
  36773. delta = bottomValue - this.average;
  36774. this.average -= delta / (this._sampleCount - 1);
  36775. this._m2 -= delta * (bottomValue - this.average);
  36776. }
  36777. else {
  36778. this._sampleCount++;
  36779. }
  36780. //add new value to mean
  36781. delta = v - this.average;
  36782. this.average += delta / (this._sampleCount);
  36783. this._m2 += delta * (v - this.average);
  36784. //set the new variance
  36785. this.variance = this._m2 / (this._sampleCount - 1);
  36786. this._samples[this._pos] = v;
  36787. this._pos++;
  36788. this._pos %= this._samples.length; //positive wrap around
  36789. };
  36790. /**
  36791. * Returns previously added values or null if outside of history or outside the sliding window domain
  36792. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36793. * @return Value previously recorded with add() or null if outside of range
  36794. */
  36795. RollingAverage.prototype.history = function (i) {
  36796. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36797. return 0;
  36798. }
  36799. var i0 = this._wrapPosition(this._pos - 1.0);
  36800. return this._samples[this._wrapPosition(i0 - i)];
  36801. };
  36802. /**
  36803. * Returns true if enough samples have been taken to completely fill the sliding window
  36804. * @return true if sample-set saturated
  36805. */
  36806. RollingAverage.prototype.isSaturated = function () {
  36807. return this._sampleCount >= this._samples.length;
  36808. };
  36809. /**
  36810. * Resets the rolling average (equivalent to 0 samples taken so far)
  36811. */
  36812. RollingAverage.prototype.reset = function () {
  36813. this.average = 0;
  36814. this.variance = 0;
  36815. this._sampleCount = 0;
  36816. this._pos = 0;
  36817. this._m2 = 0;
  36818. };
  36819. /**
  36820. * Wraps a value around the sample range boundaries
  36821. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36822. * @return Wrapped position in sample range
  36823. */
  36824. RollingAverage.prototype._wrapPosition = function (i) {
  36825. var max = this._samples.length;
  36826. return ((i % max) + max) % max;
  36827. };
  36828. return RollingAverage;
  36829. }());
  36830. BABYLON.RollingAverage = RollingAverage;
  36831. })(BABYLON || (BABYLON = {}));
  36832. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36833. var BABYLON;
  36834. (function (BABYLON) {
  36835. /**
  36836. * This groups together the common properties used for image processing either in direct forward pass
  36837. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36838. * or not.
  36839. */
  36840. var ImageProcessingConfiguration = /** @class */ (function () {
  36841. function ImageProcessingConfiguration() {
  36842. /**
  36843. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36844. */
  36845. this.colorCurves = new BABYLON.ColorCurves();
  36846. this._colorCurvesEnabled = false;
  36847. this._colorGradingEnabled = false;
  36848. this._colorGradingWithGreenDepth = true;
  36849. this._colorGradingBGR = true;
  36850. this._exposure = 1.0;
  36851. this._toneMappingEnabled = false;
  36852. this._contrast = 1.0;
  36853. /**
  36854. * Vignette stretch size.
  36855. */
  36856. this.vignetteStretch = 0;
  36857. /**
  36858. * Vignette centre X Offset.
  36859. */
  36860. this.vignetteCentreX = 0;
  36861. /**
  36862. * Vignette centre Y Offset.
  36863. */
  36864. this.vignetteCentreY = 0;
  36865. /**
  36866. * Vignette weight or intensity of the vignette effect.
  36867. */
  36868. this.vignetteWeight = 1.5;
  36869. /**
  36870. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36871. * if vignetteEnabled is set to true.
  36872. */
  36873. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36874. /**
  36875. * Camera field of view used by the Vignette effect.
  36876. */
  36877. this.vignetteCameraFov = 0.5;
  36878. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36879. this._vignetteEnabled = false;
  36880. this._applyByPostProcess = false;
  36881. this._isEnabled = true;
  36882. /**
  36883. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36884. * @type {BABYLON.Observable}
  36885. */
  36886. this.onUpdateParameters = new BABYLON.Observable();
  36887. }
  36888. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36889. /**
  36890. * Gets wether the color curves effect is enabled.
  36891. */
  36892. get: function () {
  36893. return this._colorCurvesEnabled;
  36894. },
  36895. /**
  36896. * Sets wether the color curves effect is enabled.
  36897. */
  36898. set: function (value) {
  36899. if (this._colorCurvesEnabled === value) {
  36900. return;
  36901. }
  36902. this._colorCurvesEnabled = value;
  36903. this._updateParameters();
  36904. },
  36905. enumerable: true,
  36906. configurable: true
  36907. });
  36908. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36909. /**
  36910. * Gets wether the color grading effect is enabled.
  36911. */
  36912. get: function () {
  36913. return this._colorGradingEnabled;
  36914. },
  36915. /**
  36916. * Sets wether the color grading effect is enabled.
  36917. */
  36918. set: function (value) {
  36919. if (this._colorGradingEnabled === value) {
  36920. return;
  36921. }
  36922. this._colorGradingEnabled = value;
  36923. this._updateParameters();
  36924. },
  36925. enumerable: true,
  36926. configurable: true
  36927. });
  36928. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36929. /**
  36930. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36931. */
  36932. get: function () {
  36933. return this._colorGradingWithGreenDepth;
  36934. },
  36935. /**
  36936. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36937. */
  36938. set: function (value) {
  36939. if (this._colorGradingWithGreenDepth === value) {
  36940. return;
  36941. }
  36942. this._colorGradingWithGreenDepth = value;
  36943. this._updateParameters();
  36944. },
  36945. enumerable: true,
  36946. configurable: true
  36947. });
  36948. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36949. /**
  36950. * Gets wether the color grading texture contains BGR values.
  36951. */
  36952. get: function () {
  36953. return this._colorGradingBGR;
  36954. },
  36955. /**
  36956. * Sets wether the color grading texture contains BGR values.
  36957. */
  36958. set: function (value) {
  36959. if (this._colorGradingBGR === value) {
  36960. return;
  36961. }
  36962. this._colorGradingBGR = value;
  36963. this._updateParameters();
  36964. },
  36965. enumerable: true,
  36966. configurable: true
  36967. });
  36968. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36969. /**
  36970. * Gets the Exposure used in the effect.
  36971. */
  36972. get: function () {
  36973. return this._exposure;
  36974. },
  36975. /**
  36976. * Sets the Exposure used in the effect.
  36977. */
  36978. set: function (value) {
  36979. if (this._exposure === value) {
  36980. return;
  36981. }
  36982. this._exposure = value;
  36983. this._updateParameters();
  36984. },
  36985. enumerable: true,
  36986. configurable: true
  36987. });
  36988. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36989. /**
  36990. * Gets wether the tone mapping effect is enabled.
  36991. */
  36992. get: function () {
  36993. return this._toneMappingEnabled;
  36994. },
  36995. /**
  36996. * Sets wether the tone mapping effect is enabled.
  36997. */
  36998. set: function (value) {
  36999. if (this._toneMappingEnabled === value) {
  37000. return;
  37001. }
  37002. this._toneMappingEnabled = value;
  37003. this._updateParameters();
  37004. },
  37005. enumerable: true,
  37006. configurable: true
  37007. });
  37008. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37009. /**
  37010. * Gets the contrast used in the effect.
  37011. */
  37012. get: function () {
  37013. return this._contrast;
  37014. },
  37015. /**
  37016. * Sets the contrast used in the effect.
  37017. */
  37018. set: function (value) {
  37019. if (this._contrast === value) {
  37020. return;
  37021. }
  37022. this._contrast = value;
  37023. this._updateParameters();
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37029. /**
  37030. * Gets the vignette blend mode allowing different kind of effect.
  37031. */
  37032. get: function () {
  37033. return this._vignetteBlendMode;
  37034. },
  37035. /**
  37036. * Sets the vignette blend mode allowing different kind of effect.
  37037. */
  37038. set: function (value) {
  37039. if (this._vignetteBlendMode === value) {
  37040. return;
  37041. }
  37042. this._vignetteBlendMode = value;
  37043. this._updateParameters();
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37049. /**
  37050. * Gets wether the vignette effect is enabled.
  37051. */
  37052. get: function () {
  37053. return this._vignetteEnabled;
  37054. },
  37055. /**
  37056. * Sets wether the vignette effect is enabled.
  37057. */
  37058. set: function (value) {
  37059. if (this._vignetteEnabled === value) {
  37060. return;
  37061. }
  37062. this._vignetteEnabled = value;
  37063. this._updateParameters();
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37069. /**
  37070. * Gets wether the image processing is applied through a post process or not.
  37071. */
  37072. get: function () {
  37073. return this._applyByPostProcess;
  37074. },
  37075. /**
  37076. * Sets wether the image processing is applied through a post process or not.
  37077. */
  37078. set: function (value) {
  37079. if (this._applyByPostProcess === value) {
  37080. return;
  37081. }
  37082. this._applyByPostProcess = value;
  37083. this._updateParameters();
  37084. },
  37085. enumerable: true,
  37086. configurable: true
  37087. });
  37088. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37089. /**
  37090. * Gets wether the image processing is enabled or not.
  37091. */
  37092. get: function () {
  37093. return this._isEnabled;
  37094. },
  37095. /**
  37096. * Sets wether the image processing is enabled or not.
  37097. */
  37098. set: function (value) {
  37099. if (this._isEnabled === value) {
  37100. return;
  37101. }
  37102. this._isEnabled = value;
  37103. this._updateParameters();
  37104. },
  37105. enumerable: true,
  37106. configurable: true
  37107. });
  37108. /**
  37109. * Method called each time the image processing information changes requires to recompile the effect.
  37110. */
  37111. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37112. this.onUpdateParameters.notifyObservers(this);
  37113. };
  37114. ImageProcessingConfiguration.prototype.getClassName = function () {
  37115. return "ImageProcessingConfiguration";
  37116. };
  37117. /**
  37118. * Prepare the list of uniforms associated with the Image Processing effects.
  37119. * @param uniformsList The list of uniforms used in the effect
  37120. * @param defines the list of defines currently in use
  37121. */
  37122. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37123. if (defines.EXPOSURE) {
  37124. uniforms.push("exposureLinear");
  37125. }
  37126. if (defines.CONTRAST) {
  37127. uniforms.push("contrast");
  37128. }
  37129. if (defines.COLORGRADING) {
  37130. uniforms.push("colorTransformSettings");
  37131. }
  37132. if (defines.VIGNETTE) {
  37133. uniforms.push("vInverseScreenSize");
  37134. uniforms.push("vignetteSettings1");
  37135. uniforms.push("vignetteSettings2");
  37136. }
  37137. if (defines.COLORCURVES) {
  37138. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37139. }
  37140. };
  37141. /**
  37142. * Prepare the list of samplers associated with the Image Processing effects.
  37143. * @param uniformsList The list of uniforms used in the effect
  37144. * @param defines the list of defines currently in use
  37145. */
  37146. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37147. if (defines.COLORGRADING) {
  37148. samplersList.push("txColorTransform");
  37149. }
  37150. };
  37151. /**
  37152. * Prepare the list of defines associated to the shader.
  37153. * @param defines the list of defines to complete
  37154. */
  37155. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37156. if (forPostProcess === void 0) { forPostProcess = false; }
  37157. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37158. defines.VIGNETTE = false;
  37159. defines.TONEMAPPING = false;
  37160. defines.CONTRAST = false;
  37161. defines.EXPOSURE = false;
  37162. defines.COLORCURVES = false;
  37163. defines.COLORGRADING = false;
  37164. defines.COLORGRADING3D = false;
  37165. defines.IMAGEPROCESSING = false;
  37166. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37167. return;
  37168. }
  37169. defines.VIGNETTE = this.vignetteEnabled;
  37170. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37171. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37172. defines.TONEMAPPING = this.toneMappingEnabled;
  37173. defines.CONTRAST = (this.contrast !== 1.0);
  37174. defines.EXPOSURE = (this.exposure !== 1.0);
  37175. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37176. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37177. if (defines.COLORGRADING) {
  37178. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37179. }
  37180. else {
  37181. defines.COLORGRADING3D = false;
  37182. }
  37183. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37184. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37185. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37186. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37187. };
  37188. /**
  37189. * Returns true if all the image processing information are ready.
  37190. */
  37191. ImageProcessingConfiguration.prototype.isReady = function () {
  37192. // Color Grading texure can not be none blocking.
  37193. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37194. };
  37195. /**
  37196. * Binds the image processing to the shader.
  37197. * @param effect The effect to bind to
  37198. */
  37199. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37200. if (aspectRatio === void 0) { aspectRatio = 1; }
  37201. // Color Curves
  37202. if (this._colorCurvesEnabled && this.colorCurves) {
  37203. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37204. }
  37205. // Vignette
  37206. if (this._vignetteEnabled) {
  37207. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37208. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37209. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37210. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37211. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37212. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37213. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37214. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37215. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37216. var vignettePower = -2.0 * this.vignetteWeight;
  37217. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37218. }
  37219. // Exposure
  37220. effect.setFloat("exposureLinear", this.exposure);
  37221. // Contrast
  37222. effect.setFloat("contrast", this.contrast);
  37223. // Color transform settings
  37224. if (this.colorGradingTexture) {
  37225. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37226. var textureSize = this.colorGradingTexture.getSize().height;
  37227. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37228. 0.5 / textureSize, // textureOffset
  37229. textureSize, // textureSize
  37230. this.colorGradingTexture.level // weight
  37231. );
  37232. }
  37233. };
  37234. /**
  37235. * Clones the current image processing instance.
  37236. * @return The cloned image processing
  37237. */
  37238. ImageProcessingConfiguration.prototype.clone = function () {
  37239. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37240. };
  37241. /**
  37242. * Serializes the current image processing instance to a json representation.
  37243. * @return a JSON representation
  37244. */
  37245. ImageProcessingConfiguration.prototype.serialize = function () {
  37246. return BABYLON.SerializationHelper.Serialize(this);
  37247. };
  37248. /**
  37249. * Parses the image processing from a json representation.
  37250. * @param source the JSON source to parse
  37251. * @return The parsed image processing
  37252. */
  37253. ImageProcessingConfiguration.Parse = function (source) {
  37254. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37255. };
  37256. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37257. /**
  37258. * Used to apply the vignette as a mix with the pixel color.
  37259. */
  37260. get: function () {
  37261. return this._VIGNETTEMODE_MULTIPLY;
  37262. },
  37263. enumerable: true,
  37264. configurable: true
  37265. });
  37266. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37267. /**
  37268. * Used to apply the vignette as a replacement of the pixel color.
  37269. */
  37270. get: function () {
  37271. return this._VIGNETTEMODE_OPAQUE;
  37272. },
  37273. enumerable: true,
  37274. configurable: true
  37275. });
  37276. // Static constants associated to the image processing.
  37277. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37278. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37279. __decorate([
  37280. BABYLON.serializeAsColorCurves()
  37281. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37282. __decorate([
  37283. BABYLON.serialize()
  37284. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37285. __decorate([
  37286. BABYLON.serializeAsTexture()
  37287. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37288. __decorate([
  37289. BABYLON.serialize()
  37290. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37291. __decorate([
  37292. BABYLON.serialize()
  37293. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37294. __decorate([
  37295. BABYLON.serialize()
  37296. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37297. __decorate([
  37298. BABYLON.serialize()
  37299. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37300. __decorate([
  37301. BABYLON.serialize()
  37302. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37303. __decorate([
  37304. BABYLON.serialize()
  37305. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37306. __decorate([
  37307. BABYLON.serialize()
  37308. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37309. __decorate([
  37310. BABYLON.serialize()
  37311. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37312. __decorate([
  37313. BABYLON.serialize()
  37314. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37315. __decorate([
  37316. BABYLON.serialize()
  37317. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37318. __decorate([
  37319. BABYLON.serializeAsColor4()
  37320. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37321. __decorate([
  37322. BABYLON.serialize()
  37323. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37324. __decorate([
  37325. BABYLON.serialize()
  37326. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37327. __decorate([
  37328. BABYLON.serialize()
  37329. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37330. __decorate([
  37331. BABYLON.serialize()
  37332. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37333. __decorate([
  37334. BABYLON.serialize()
  37335. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37336. return ImageProcessingConfiguration;
  37337. }());
  37338. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37339. })(BABYLON || (BABYLON = {}));
  37340. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37341. var BABYLON;
  37342. (function (BABYLON) {
  37343. /**
  37344. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37345. * It can help converting any input color in a desired output one. This can then be used to create effects
  37346. * from sepia, black and white to sixties or futuristic rendering...
  37347. *
  37348. * The only supported format is currently 3dl.
  37349. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37350. */
  37351. var ColorGradingTexture = /** @class */ (function (_super) {
  37352. __extends(ColorGradingTexture, _super);
  37353. /**
  37354. * Instantiates a ColorGradingTexture from the following parameters.
  37355. *
  37356. * @param url The location of the color gradind data (currently only supporting 3dl)
  37357. * @param scene The scene the texture will be used in
  37358. */
  37359. function ColorGradingTexture(url, scene) {
  37360. var _this = _super.call(this, scene) || this;
  37361. if (!url) {
  37362. return _this;
  37363. }
  37364. _this._engine = scene.getEngine();
  37365. _this._textureMatrix = BABYLON.Matrix.Identity();
  37366. _this.name = url;
  37367. _this.url = url;
  37368. _this.hasAlpha = false;
  37369. _this.isCube = false;
  37370. _this.is3D = _this._engine.webGLVersion > 1;
  37371. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37372. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37373. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37374. _this.anisotropicFilteringLevel = 1;
  37375. _this._texture = _this._getFromCache(url, true);
  37376. if (!_this._texture) {
  37377. if (!scene.useDelayedTextureLoading) {
  37378. _this.loadTexture();
  37379. }
  37380. else {
  37381. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37382. }
  37383. }
  37384. return _this;
  37385. }
  37386. /**
  37387. * Returns the texture matrix used in most of the material.
  37388. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37389. */
  37390. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37391. return this._textureMatrix;
  37392. };
  37393. /**
  37394. * Occurs when the file being loaded is a .3dl LUT file.
  37395. */
  37396. ColorGradingTexture.prototype.load3dlTexture = function () {
  37397. var engine = this._engine;
  37398. var texture;
  37399. if (engine.webGLVersion === 1) {
  37400. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37401. }
  37402. else {
  37403. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37404. }
  37405. this._texture = texture;
  37406. var callback = function (text) {
  37407. if (typeof text !== "string") {
  37408. return;
  37409. }
  37410. var data = null;
  37411. var tempData = null;
  37412. var line;
  37413. var lines = text.split('\n');
  37414. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37415. var maxColor = 0;
  37416. for (var i = 0; i < lines.length; i++) {
  37417. line = lines[i];
  37418. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37419. continue;
  37420. if (line.indexOf('#') === 0)
  37421. continue;
  37422. var words = line.split(" ");
  37423. if (size === 0) {
  37424. // Number of space + one
  37425. size = words.length;
  37426. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37427. tempData = new Float32Array(size * size * size * 4);
  37428. continue;
  37429. }
  37430. if (size != 0) {
  37431. var r = Math.max(parseInt(words[0]), 0);
  37432. var g = Math.max(parseInt(words[1]), 0);
  37433. var b = Math.max(parseInt(words[2]), 0);
  37434. maxColor = Math.max(r, maxColor);
  37435. maxColor = Math.max(g, maxColor);
  37436. maxColor = Math.max(b, maxColor);
  37437. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37438. if (tempData) {
  37439. tempData[pixelStorageIndex + 0] = r;
  37440. tempData[pixelStorageIndex + 1] = g;
  37441. tempData[pixelStorageIndex + 2] = b;
  37442. }
  37443. pixelIndexSlice++;
  37444. if (pixelIndexSlice % size == 0) {
  37445. pixelIndexH++;
  37446. pixelIndexSlice = 0;
  37447. if (pixelIndexH % size == 0) {
  37448. pixelIndexW++;
  37449. pixelIndexH = 0;
  37450. }
  37451. }
  37452. }
  37453. }
  37454. if (tempData && data) {
  37455. for (var i = 0; i < tempData.length; i++) {
  37456. if (i > 0 && (i + 1) % 4 === 0) {
  37457. data[i] = 255;
  37458. }
  37459. else {
  37460. var value = tempData[i];
  37461. data[i] = (value / maxColor * 255);
  37462. }
  37463. }
  37464. }
  37465. if (texture.is3D) {
  37466. texture.updateSize(size, size, size);
  37467. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37468. }
  37469. else {
  37470. texture.updateSize(size * size, size);
  37471. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37472. }
  37473. };
  37474. var scene = this.getScene();
  37475. if (scene) {
  37476. scene._loadFile(this.url, callback);
  37477. }
  37478. else {
  37479. this._engine._loadFile(this.url, callback);
  37480. }
  37481. return this._texture;
  37482. };
  37483. /**
  37484. * Starts the loading process of the texture.
  37485. */
  37486. ColorGradingTexture.prototype.loadTexture = function () {
  37487. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37488. this.load3dlTexture();
  37489. }
  37490. };
  37491. /**
  37492. * Clones the color gradind texture.
  37493. */
  37494. ColorGradingTexture.prototype.clone = function () {
  37495. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37496. // Base texture
  37497. newTexture.level = this.level;
  37498. return newTexture;
  37499. };
  37500. /**
  37501. * Called during delayed load for textures.
  37502. */
  37503. ColorGradingTexture.prototype.delayLoad = function () {
  37504. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37505. return;
  37506. }
  37507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37508. this._texture = this._getFromCache(this.url, true);
  37509. if (!this._texture) {
  37510. this.loadTexture();
  37511. }
  37512. };
  37513. /**
  37514. * Parses a color grading texture serialized by Babylon.
  37515. * @param parsedTexture The texture information being parsedTexture
  37516. * @param scene The scene to load the texture in
  37517. * @param rootUrl The root url of the data assets to load
  37518. * @return A color gradind texture
  37519. */
  37520. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37521. var texture = null;
  37522. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37523. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37524. texture.name = parsedTexture.name;
  37525. texture.level = parsedTexture.level;
  37526. }
  37527. return texture;
  37528. };
  37529. /**
  37530. * Serializes the LUT texture to json format.
  37531. */
  37532. ColorGradingTexture.prototype.serialize = function () {
  37533. if (!this.name) {
  37534. return null;
  37535. }
  37536. var serializationObject = {};
  37537. serializationObject.name = this.name;
  37538. serializationObject.level = this.level;
  37539. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37540. return serializationObject;
  37541. };
  37542. /**
  37543. * Empty line regex stored for GC.
  37544. */
  37545. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37546. return ColorGradingTexture;
  37547. }(BABYLON.BaseTexture));
  37548. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37549. })(BABYLON || (BABYLON = {}));
  37550. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37551. var BABYLON;
  37552. (function (BABYLON) {
  37553. /**
  37554. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37555. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37556. * 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;
  37557. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37558. */
  37559. var ColorCurves = /** @class */ (function () {
  37560. function ColorCurves() {
  37561. this._dirty = true;
  37562. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37563. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37564. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37565. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37566. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37567. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37568. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37569. this._globalHue = 30;
  37570. this._globalDensity = 0;
  37571. this._globalSaturation = 0;
  37572. this._globalExposure = 0;
  37573. this._highlightsHue = 30;
  37574. this._highlightsDensity = 0;
  37575. this._highlightsSaturation = 0;
  37576. this._highlightsExposure = 0;
  37577. this._midtonesHue = 30;
  37578. this._midtonesDensity = 0;
  37579. this._midtonesSaturation = 0;
  37580. this._midtonesExposure = 0;
  37581. this._shadowsHue = 30;
  37582. this._shadowsDensity = 0;
  37583. this._shadowsSaturation = 0;
  37584. this._shadowsExposure = 0;
  37585. }
  37586. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37587. /**
  37588. * Gets the global Hue value.
  37589. * 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).
  37590. */
  37591. get: function () {
  37592. return this._globalHue;
  37593. },
  37594. /**
  37595. * Sets the global Hue value.
  37596. * 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).
  37597. */
  37598. set: function (value) {
  37599. this._globalHue = value;
  37600. this._dirty = true;
  37601. },
  37602. enumerable: true,
  37603. configurable: true
  37604. });
  37605. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37606. /**
  37607. * Gets the global Density value.
  37608. * 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.
  37609. * Values less than zero provide a filter of opposite hue.
  37610. */
  37611. get: function () {
  37612. return this._globalDensity;
  37613. },
  37614. /**
  37615. * Sets the global Density value.
  37616. * 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.
  37617. * Values less than zero provide a filter of opposite hue.
  37618. */
  37619. set: function (value) {
  37620. this._globalDensity = value;
  37621. this._dirty = true;
  37622. },
  37623. enumerable: true,
  37624. configurable: true
  37625. });
  37626. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37627. /**
  37628. * Gets the global Saturation value.
  37629. * 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.
  37630. */
  37631. get: function () {
  37632. return this._globalSaturation;
  37633. },
  37634. /**
  37635. * Sets the global Saturation value.
  37636. * 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.
  37637. */
  37638. set: function (value) {
  37639. this._globalSaturation = value;
  37640. this._dirty = true;
  37641. },
  37642. enumerable: true,
  37643. configurable: true
  37644. });
  37645. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37646. /**
  37647. * Gets the highlights Hue value.
  37648. * 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).
  37649. */
  37650. get: function () {
  37651. return this._highlightsHue;
  37652. },
  37653. /**
  37654. * Sets the highlights Hue value.
  37655. * 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).
  37656. */
  37657. set: function (value) {
  37658. this._highlightsHue = value;
  37659. this._dirty = true;
  37660. },
  37661. enumerable: true,
  37662. configurable: true
  37663. });
  37664. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37665. /**
  37666. * Gets the highlights Density value.
  37667. * 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.
  37668. * Values less than zero provide a filter of opposite hue.
  37669. */
  37670. get: function () {
  37671. return this._highlightsDensity;
  37672. },
  37673. /**
  37674. * Sets the highlights Density value.
  37675. * 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.
  37676. * Values less than zero provide a filter of opposite hue.
  37677. */
  37678. set: function (value) {
  37679. this._highlightsDensity = value;
  37680. this._dirty = true;
  37681. },
  37682. enumerable: true,
  37683. configurable: true
  37684. });
  37685. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37686. /**
  37687. * Gets the highlights Saturation value.
  37688. * 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.
  37689. */
  37690. get: function () {
  37691. return this._highlightsSaturation;
  37692. },
  37693. /**
  37694. * Sets the highlights Saturation value.
  37695. * 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.
  37696. */
  37697. set: function (value) {
  37698. this._highlightsSaturation = value;
  37699. this._dirty = true;
  37700. },
  37701. enumerable: true,
  37702. configurable: true
  37703. });
  37704. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37705. /**
  37706. * Gets the highlights Exposure value.
  37707. * 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.
  37708. */
  37709. get: function () {
  37710. return this._highlightsExposure;
  37711. },
  37712. /**
  37713. * Sets the highlights Exposure value.
  37714. * 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.
  37715. */
  37716. set: function (value) {
  37717. this._highlightsExposure = value;
  37718. this._dirty = true;
  37719. },
  37720. enumerable: true,
  37721. configurable: true
  37722. });
  37723. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37724. /**
  37725. * Gets the midtones Hue value.
  37726. * 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).
  37727. */
  37728. get: function () {
  37729. return this._midtonesHue;
  37730. },
  37731. /**
  37732. * Sets the midtones Hue value.
  37733. * 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).
  37734. */
  37735. set: function (value) {
  37736. this._midtonesHue = value;
  37737. this._dirty = true;
  37738. },
  37739. enumerable: true,
  37740. configurable: true
  37741. });
  37742. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37743. /**
  37744. * Gets the midtones Density value.
  37745. * 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.
  37746. * Values less than zero provide a filter of opposite hue.
  37747. */
  37748. get: function () {
  37749. return this._midtonesDensity;
  37750. },
  37751. /**
  37752. * Sets the midtones Density value.
  37753. * 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.
  37754. * Values less than zero provide a filter of opposite hue.
  37755. */
  37756. set: function (value) {
  37757. this._midtonesDensity = value;
  37758. this._dirty = true;
  37759. },
  37760. enumerable: true,
  37761. configurable: true
  37762. });
  37763. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37764. /**
  37765. * Gets the midtones Saturation value.
  37766. * 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.
  37767. */
  37768. get: function () {
  37769. return this._midtonesSaturation;
  37770. },
  37771. /**
  37772. * Sets the midtones Saturation value.
  37773. * 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.
  37774. */
  37775. set: function (value) {
  37776. this._midtonesSaturation = value;
  37777. this._dirty = true;
  37778. },
  37779. enumerable: true,
  37780. configurable: true
  37781. });
  37782. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37783. /**
  37784. * Gets the midtones Exposure value.
  37785. * 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.
  37786. */
  37787. get: function () {
  37788. return this._midtonesExposure;
  37789. },
  37790. /**
  37791. * Sets the midtones Exposure value.
  37792. * 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.
  37793. */
  37794. set: function (value) {
  37795. this._midtonesExposure = value;
  37796. this._dirty = true;
  37797. },
  37798. enumerable: true,
  37799. configurable: true
  37800. });
  37801. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37802. /**
  37803. * Gets the shadows Hue value.
  37804. * 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).
  37805. */
  37806. get: function () {
  37807. return this._shadowsHue;
  37808. },
  37809. /**
  37810. * Sets the shadows Hue value.
  37811. * 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).
  37812. */
  37813. set: function (value) {
  37814. this._shadowsHue = value;
  37815. this._dirty = true;
  37816. },
  37817. enumerable: true,
  37818. configurable: true
  37819. });
  37820. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37821. /**
  37822. * Gets the shadows Density value.
  37823. * 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.
  37824. * Values less than zero provide a filter of opposite hue.
  37825. */
  37826. get: function () {
  37827. return this._shadowsDensity;
  37828. },
  37829. /**
  37830. * Sets the shadows Density value.
  37831. * 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.
  37832. * Values less than zero provide a filter of opposite hue.
  37833. */
  37834. set: function (value) {
  37835. this._shadowsDensity = value;
  37836. this._dirty = true;
  37837. },
  37838. enumerable: true,
  37839. configurable: true
  37840. });
  37841. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37842. /**
  37843. * Gets the shadows Saturation value.
  37844. * 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.
  37845. */
  37846. get: function () {
  37847. return this._shadowsSaturation;
  37848. },
  37849. /**
  37850. * Sets the shadows Saturation value.
  37851. * 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.
  37852. */
  37853. set: function (value) {
  37854. this._shadowsSaturation = value;
  37855. this._dirty = true;
  37856. },
  37857. enumerable: true,
  37858. configurable: true
  37859. });
  37860. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37861. /**
  37862. * Gets the shadows Exposure value.
  37863. * 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.
  37864. */
  37865. get: function () {
  37866. return this._shadowsExposure;
  37867. },
  37868. /**
  37869. * Sets the shadows Exposure value.
  37870. * 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.
  37871. */
  37872. set: function (value) {
  37873. this._shadowsExposure = value;
  37874. this._dirty = true;
  37875. },
  37876. enumerable: true,
  37877. configurable: true
  37878. });
  37879. ColorCurves.prototype.getClassName = function () {
  37880. return "ColorCurves";
  37881. };
  37882. /**
  37883. * Binds the color curves to the shader.
  37884. * @param colorCurves The color curve to bind
  37885. * @param effect The effect to bind to
  37886. */
  37887. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37888. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37889. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37890. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37891. if (colorCurves._dirty) {
  37892. colorCurves._dirty = false;
  37893. // Fill in global info.
  37894. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37895. // Compute highlights info.
  37896. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37897. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37898. // Compute midtones info.
  37899. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37900. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37901. // Compute shadows info.
  37902. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37903. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37904. // Compute deltas (neutral is midtones).
  37905. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37906. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37907. }
  37908. if (effect) {
  37909. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37910. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37911. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37912. }
  37913. };
  37914. /**
  37915. * Prepare the list of uniforms associated with the ColorCurves effects.
  37916. * @param uniformsList The list of uniforms used in the effect
  37917. */
  37918. ColorCurves.PrepareUniforms = function (uniformsList) {
  37919. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37920. };
  37921. /**
  37922. * Returns color grading data based on a hue, density, saturation and exposure value.
  37923. * @param filterHue The hue of the color filter.
  37924. * @param filterDensity The density of the color filter.
  37925. * @param saturation The saturation.
  37926. * @param exposure The exposure.
  37927. * @param result The result data container.
  37928. */
  37929. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37930. if (hue == null) {
  37931. return;
  37932. }
  37933. hue = ColorCurves.clamp(hue, 0, 360);
  37934. density = ColorCurves.clamp(density, -100, 100);
  37935. saturation = ColorCurves.clamp(saturation, -100, 100);
  37936. exposure = ColorCurves.clamp(exposure, -100, 100);
  37937. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37938. // so that the maximum filter density is only 50% control. This provides fine control
  37939. // for small values and reasonable range.
  37940. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37941. density *= 0.5;
  37942. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37943. if (density < 0) {
  37944. density *= -1;
  37945. hue = (hue + 180) % 360;
  37946. }
  37947. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37948. result.scaleToRef(2, result);
  37949. result.a = 1 + 0.01 * saturation;
  37950. };
  37951. /**
  37952. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37953. * @param value The input slider value in range [-100,100].
  37954. * @returns Adjusted value.
  37955. */
  37956. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37957. value /= 100;
  37958. var x = Math.abs(value);
  37959. x = Math.pow(x, 2);
  37960. if (value < 0) {
  37961. x *= -1;
  37962. }
  37963. x *= 100;
  37964. return x;
  37965. };
  37966. /**
  37967. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37968. * @param hue The hue (H) input.
  37969. * @param saturation The saturation (S) input.
  37970. * @param brightness The brightness (B) input.
  37971. * @result An RGBA color represented as Vector4.
  37972. */
  37973. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37974. var h = ColorCurves.clamp(hue, 0, 360);
  37975. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37976. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37977. if (s === 0) {
  37978. result.r = v;
  37979. result.g = v;
  37980. result.b = v;
  37981. }
  37982. else {
  37983. // sector 0 to 5
  37984. h /= 60;
  37985. var i = Math.floor(h);
  37986. // fractional part of h
  37987. var f = h - i;
  37988. var p = v * (1 - s);
  37989. var q = v * (1 - s * f);
  37990. var t = v * (1 - s * (1 - f));
  37991. switch (i) {
  37992. case 0:
  37993. result.r = v;
  37994. result.g = t;
  37995. result.b = p;
  37996. break;
  37997. case 1:
  37998. result.r = q;
  37999. result.g = v;
  38000. result.b = p;
  38001. break;
  38002. case 2:
  38003. result.r = p;
  38004. result.g = v;
  38005. result.b = t;
  38006. break;
  38007. case 3:
  38008. result.r = p;
  38009. result.g = q;
  38010. result.b = v;
  38011. break;
  38012. case 4:
  38013. result.r = t;
  38014. result.g = p;
  38015. result.b = v;
  38016. break;
  38017. default:// case 5:
  38018. result.r = v;
  38019. result.g = p;
  38020. result.b = q;
  38021. break;
  38022. }
  38023. }
  38024. result.a = 1;
  38025. };
  38026. /**
  38027. * Returns a value clamped between min and max
  38028. * @param value The value to clamp
  38029. * @param min The minimum of value
  38030. * @param max The maximum of value
  38031. * @returns The clamped value.
  38032. */
  38033. ColorCurves.clamp = function (value, min, max) {
  38034. return Math.min(Math.max(value, min), max);
  38035. };
  38036. /**
  38037. * Clones the current color curve instance.
  38038. * @return The cloned curves
  38039. */
  38040. ColorCurves.prototype.clone = function () {
  38041. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38042. };
  38043. /**
  38044. * Serializes the current color curve instance to a json representation.
  38045. * @return a JSON representation
  38046. */
  38047. ColorCurves.prototype.serialize = function () {
  38048. return BABYLON.SerializationHelper.Serialize(this);
  38049. };
  38050. /**
  38051. * Parses the color curve from a json representation.
  38052. * @param source the JSON source to parse
  38053. * @return The parsed curves
  38054. */
  38055. ColorCurves.Parse = function (source) {
  38056. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38057. };
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], ColorCurves.prototype, "_globalHue", void 0);
  38061. __decorate([
  38062. BABYLON.serialize()
  38063. ], ColorCurves.prototype, "_globalDensity", void 0);
  38064. __decorate([
  38065. BABYLON.serialize()
  38066. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38067. __decorate([
  38068. BABYLON.serialize()
  38069. ], ColorCurves.prototype, "_globalExposure", void 0);
  38070. __decorate([
  38071. BABYLON.serialize()
  38072. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38073. __decorate([
  38074. BABYLON.serialize()
  38075. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38076. __decorate([
  38077. BABYLON.serialize()
  38078. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38079. __decorate([
  38080. BABYLON.serialize()
  38081. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38082. __decorate([
  38083. BABYLON.serialize()
  38084. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38085. __decorate([
  38086. BABYLON.serialize()
  38087. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38088. __decorate([
  38089. BABYLON.serialize()
  38090. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38091. __decorate([
  38092. BABYLON.serialize()
  38093. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38094. return ColorCurves;
  38095. }());
  38096. BABYLON.ColorCurves = ColorCurves;
  38097. })(BABYLON || (BABYLON = {}));
  38098. //# sourceMappingURL=babylon.colorCurves.js.map
  38099. //# sourceMappingURL=babylon.behavior.js.map
  38100. var BABYLON;
  38101. (function (BABYLON) {
  38102. /**
  38103. * "Static Class" containing the most commonly used helper while dealing with material for
  38104. * rendering purpose.
  38105. *
  38106. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38107. *
  38108. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38109. */
  38110. var MaterialHelper = /** @class */ (function () {
  38111. function MaterialHelper() {
  38112. }
  38113. /**
  38114. * Bind the current view position to an effect.
  38115. * @param effect The effect to be bound
  38116. * @param scene The scene the eyes position is used from
  38117. */
  38118. MaterialHelper.BindEyePosition = function (effect, scene) {
  38119. if (scene._forcedViewPosition) {
  38120. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38121. return;
  38122. }
  38123. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38124. };
  38125. /**
  38126. * Helps preparing the defines values about the UVs in used in the effect.
  38127. * UVs are shared as much as we can accross chanels in the shaders.
  38128. * @param texture The texture we are preparing the UVs for
  38129. * @param defines The defines to update
  38130. * @param key The chanel key "diffuse", "specular"... used in the shader
  38131. */
  38132. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38133. defines._needUVs = true;
  38134. defines[key] = true;
  38135. if (texture.getTextureMatrix().isIdentity(true)) {
  38136. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38137. if (texture.coordinatesIndex === 0) {
  38138. defines["MAINUV1"] = true;
  38139. }
  38140. else {
  38141. defines["MAINUV2"] = true;
  38142. }
  38143. }
  38144. else {
  38145. defines[key + "DIRECTUV"] = 0;
  38146. }
  38147. };
  38148. /**
  38149. * Binds a texture matrix value to its corrsponding uniform
  38150. * @param texture The texture to bind the matrix for
  38151. * @param uniformBuffer The uniform buffer receivin the data
  38152. * @param key The chanel key "diffuse", "specular"... used in the shader
  38153. */
  38154. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38155. var matrix = texture.getTextureMatrix();
  38156. if (!matrix.isIdentity(true)) {
  38157. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38158. }
  38159. };
  38160. /**
  38161. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38162. * @param mesh defines the current mesh
  38163. * @param scene defines the current scene
  38164. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38165. * @param pointsCloud defines if point cloud rendering has to be turned on
  38166. * @param fogEnabled defines if fog has to be turned on
  38167. * @param alphaTest defines if alpha testing has to be turned on
  38168. * @param defines defines the current list of defines
  38169. */
  38170. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38171. if (defines._areMiscDirty) {
  38172. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38173. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38174. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38175. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38176. defines["ALPHATEST"] = alphaTest;
  38177. }
  38178. };
  38179. /**
  38180. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38181. * @param scene defines the current scene
  38182. * @param engine defines the current engine
  38183. * @param defines specifies the list of active defines
  38184. * @param useInstances defines if instances have to be turned on
  38185. * @param useClipPlane defines if clip plane have to be turned on
  38186. */
  38187. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38188. if (useClipPlane === void 0) { useClipPlane = null; }
  38189. var changed = false;
  38190. if (useClipPlane == null) {
  38191. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38192. }
  38193. if (defines["CLIPPLANE"] !== useClipPlane) {
  38194. defines["CLIPPLANE"] = useClipPlane;
  38195. changed = true;
  38196. }
  38197. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38198. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38199. changed = true;
  38200. }
  38201. if (defines["INSTANCES"] !== useInstances) {
  38202. defines["INSTANCES"] = useInstances;
  38203. changed = true;
  38204. }
  38205. if (changed) {
  38206. defines.markAsUnprocessed();
  38207. }
  38208. };
  38209. /**
  38210. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38211. * @param mesh The mesh containing the geometry data we will draw
  38212. * @param defines The defines to update
  38213. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38214. * @param useBones Precise whether bones should be used or not (override mesh info)
  38215. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38216. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38217. * @returns false if defines are considered not dirty and have not been checked
  38218. */
  38219. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38220. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38221. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38222. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38223. return false;
  38224. }
  38225. defines._normals = defines._needNormals;
  38226. defines._uvs = defines._needUVs;
  38227. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38228. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38229. defines["TANGENT"] = true;
  38230. }
  38231. if (defines._needUVs) {
  38232. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38233. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38234. }
  38235. else {
  38236. defines["UV1"] = false;
  38237. defines["UV2"] = false;
  38238. }
  38239. if (useVertexColor) {
  38240. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38241. defines["VERTEXCOLOR"] = hasVertexColors;
  38242. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38243. }
  38244. if (useBones) {
  38245. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38246. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38247. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38248. }
  38249. else {
  38250. defines["NUM_BONE_INFLUENCERS"] = 0;
  38251. defines["BonesPerMesh"] = 0;
  38252. }
  38253. }
  38254. if (useMorphTargets) {
  38255. var manager = mesh.morphTargetManager;
  38256. if (manager) {
  38257. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38258. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38259. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38260. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38261. }
  38262. else {
  38263. defines["MORPHTARGETS_TANGENT"] = false;
  38264. defines["MORPHTARGETS_NORMAL"] = false;
  38265. defines["MORPHTARGETS"] = false;
  38266. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38267. }
  38268. }
  38269. return true;
  38270. };
  38271. /**
  38272. * Prepares the defines related to the light information passed in parameter
  38273. * @param scene The scene we are intending to draw
  38274. * @param mesh The mesh the effect is compiling for
  38275. * @param defines The defines to update
  38276. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38277. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38278. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38279. * @returns true if normals will be required for the rest of the effect
  38280. */
  38281. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38282. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38283. if (disableLighting === void 0) { disableLighting = false; }
  38284. if (!defines._areLightsDirty) {
  38285. return defines._needNormals;
  38286. }
  38287. var lightIndex = 0;
  38288. var needNormals = false;
  38289. var needRebuild = false;
  38290. var lightmapMode = false;
  38291. var shadowEnabled = false;
  38292. var specularEnabled = false;
  38293. if (scene.lightsEnabled && !disableLighting) {
  38294. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38295. var light = _a[_i];
  38296. needNormals = true;
  38297. if (defines["LIGHT" + lightIndex] === undefined) {
  38298. needRebuild = true;
  38299. }
  38300. defines["LIGHT" + lightIndex] = true;
  38301. defines["SPOTLIGHT" + lightIndex] = false;
  38302. defines["HEMILIGHT" + lightIndex] = false;
  38303. defines["POINTLIGHT" + lightIndex] = false;
  38304. defines["DIRLIGHT" + lightIndex] = false;
  38305. var type;
  38306. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38307. type = "SPOTLIGHT" + lightIndex;
  38308. var spotLight = light;
  38309. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38310. }
  38311. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38312. type = "HEMILIGHT" + lightIndex;
  38313. }
  38314. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38315. type = "POINTLIGHT" + lightIndex;
  38316. }
  38317. else {
  38318. type = "DIRLIGHT" + lightIndex;
  38319. }
  38320. defines[type] = true;
  38321. // Specular
  38322. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38323. specularEnabled = true;
  38324. }
  38325. // Shadows
  38326. defines["SHADOW" + lightIndex] = false;
  38327. defines["SHADOWPCF" + lightIndex] = false;
  38328. defines["SHADOWESM" + lightIndex] = false;
  38329. defines["SHADOWCUBE" + lightIndex] = false;
  38330. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38331. var shadowGenerator = light.getShadowGenerator();
  38332. if (shadowGenerator) {
  38333. shadowEnabled = true;
  38334. shadowGenerator.prepareDefines(defines, lightIndex);
  38335. }
  38336. }
  38337. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38338. lightmapMode = true;
  38339. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38340. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38341. }
  38342. else {
  38343. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38344. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38345. }
  38346. lightIndex++;
  38347. if (lightIndex === maxSimultaneousLights)
  38348. break;
  38349. }
  38350. }
  38351. defines["SPECULARTERM"] = specularEnabled;
  38352. defines["SHADOWS"] = shadowEnabled;
  38353. // Resetting all other lights if any
  38354. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38355. if (defines["LIGHT" + index] !== undefined) {
  38356. defines["LIGHT" + index] = false;
  38357. defines["HEMILIGHT" + lightIndex] = false;
  38358. defines["POINTLIGHT" + lightIndex] = false;
  38359. defines["DIRLIGHT" + lightIndex] = false;
  38360. defines["SPOTLIGHT" + lightIndex] = false;
  38361. defines["SHADOW" + lightIndex] = false;
  38362. }
  38363. }
  38364. var caps = scene.getEngine().getCaps();
  38365. if (defines["SHADOWFLOAT"] === undefined) {
  38366. needRebuild = true;
  38367. }
  38368. defines["SHADOWFLOAT"] = shadowEnabled &&
  38369. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38370. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38371. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38372. if (needRebuild) {
  38373. defines.rebuild();
  38374. }
  38375. return needNormals;
  38376. };
  38377. /**
  38378. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38379. * that won t be acctive due to defines being turned off.
  38380. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38381. * @param samplersList The samplers list
  38382. * @param defines The defines helping in the list generation
  38383. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38384. */
  38385. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38386. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38387. var uniformsList;
  38388. var uniformBuffersList = null;
  38389. if (uniformsListOrOptions.uniformsNames) {
  38390. var options = uniformsListOrOptions;
  38391. uniformsList = options.uniformsNames;
  38392. uniformBuffersList = options.uniformBuffersNames;
  38393. samplersList = options.samplers;
  38394. defines = options.defines;
  38395. maxSimultaneousLights = options.maxSimultaneousLights;
  38396. }
  38397. else {
  38398. uniformsList = uniformsListOrOptions;
  38399. if (!samplersList) {
  38400. samplersList = [];
  38401. }
  38402. }
  38403. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38404. if (!defines["LIGHT" + lightIndex]) {
  38405. break;
  38406. }
  38407. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38408. if (uniformBuffersList) {
  38409. uniformBuffersList.push("Light" + lightIndex);
  38410. }
  38411. samplersList.push("shadowSampler" + lightIndex);
  38412. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38413. samplersList.push("projectionLightSampler" + lightIndex);
  38414. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38415. }
  38416. }
  38417. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38418. uniformsList.push("morphTargetInfluences");
  38419. }
  38420. };
  38421. /**
  38422. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38423. * @param defines The defines to update while falling back
  38424. * @param fallbacks The authorized effect fallbacks
  38425. * @param maxSimultaneousLights The maximum number of lights allowed
  38426. * @param rank the current rank of the Effect
  38427. * @returns The newly affected rank
  38428. */
  38429. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38430. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38431. if (rank === void 0) { rank = 0; }
  38432. var lightFallbackRank = 0;
  38433. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38434. if (!defines["LIGHT" + lightIndex]) {
  38435. break;
  38436. }
  38437. if (lightIndex > 0) {
  38438. lightFallbackRank = rank + lightIndex;
  38439. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38440. }
  38441. if (!defines["SHADOWS"]) {
  38442. if (defines["SHADOW" + lightIndex]) {
  38443. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38444. }
  38445. if (defines["SHADOWPCF" + lightIndex]) {
  38446. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38447. }
  38448. if (defines["SHADOWESM" + lightIndex]) {
  38449. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38450. }
  38451. }
  38452. }
  38453. return lightFallbackRank++;
  38454. };
  38455. /**
  38456. * Prepares the list of attributes required for morph targets according to the effect defines.
  38457. * @param attribs The current list of supported attribs
  38458. * @param mesh The mesh to prepare the morph targets attributes for
  38459. * @param defines The current Defines of the effect
  38460. */
  38461. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38462. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38463. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38464. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38465. var manager = mesh.morphTargetManager;
  38466. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38467. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38468. for (var index = 0; index < influencers; index++) {
  38469. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38470. if (normal) {
  38471. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38472. }
  38473. if (tangent) {
  38474. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38475. }
  38476. if (attribs.length > maxAttributesCount) {
  38477. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38478. }
  38479. }
  38480. }
  38481. };
  38482. /**
  38483. * Prepares the list of attributes required for bones according to the effect defines.
  38484. * @param attribs The current list of supported attribs
  38485. * @param mesh The mesh to prepare the bones attributes for
  38486. * @param defines The current Defines of the effect
  38487. * @param fallbacks The current efffect fallback strategy
  38488. */
  38489. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38490. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38491. fallbacks.addCPUSkinningFallback(0, mesh);
  38492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38494. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38497. }
  38498. }
  38499. };
  38500. /**
  38501. * Prepares the list of attributes required for instances according to the effect defines.
  38502. * @param attribs The current list of supported attribs
  38503. * @param defines The current Defines of the effect
  38504. */
  38505. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38506. if (defines["INSTANCES"]) {
  38507. attribs.push("world0");
  38508. attribs.push("world1");
  38509. attribs.push("world2");
  38510. attribs.push("world3");
  38511. }
  38512. };
  38513. /**
  38514. * Binds the light shadow information to the effect for the given mesh.
  38515. * @param light The light containing the generator
  38516. * @param scene The scene the lights belongs to
  38517. * @param mesh The mesh we are binding the information to render
  38518. * @param lightIndex The light index in the effect used to render the mesh
  38519. * @param effect The effect we are binding the data to
  38520. */
  38521. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38522. if (light.shadowEnabled && mesh.receiveShadows) {
  38523. var shadowGenerator = light.getShadowGenerator();
  38524. if (shadowGenerator) {
  38525. shadowGenerator.bindShadowLight(lightIndex, effect);
  38526. }
  38527. }
  38528. };
  38529. /**
  38530. * Binds the light information to the effect.
  38531. * @param light The light containing the generator
  38532. * @param effect The effect we are binding the data to
  38533. * @param lightIndex The light index in the effect used to render
  38534. */
  38535. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38536. light.transferToEffect(effect, lightIndex + "");
  38537. };
  38538. /**
  38539. * Binds the lights information from the scene to the effect for the given mesh.
  38540. * @param scene The scene the lights belongs to
  38541. * @param mesh The mesh we are binding the information to render
  38542. * @param effect The effect we are binding the data to
  38543. * @param defines The generated defines for the effect
  38544. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38545. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38546. */
  38547. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38548. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38549. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38550. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38551. for (var i = 0; i < len; i++) {
  38552. var light = mesh._lightSources[i];
  38553. var iAsString = i.toString();
  38554. var scaledIntensity = light.getScaledIntensity();
  38555. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38556. MaterialHelper.BindLightProperties(light, effect, i);
  38557. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38558. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38559. if (defines["SPECULARTERM"]) {
  38560. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38561. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38562. }
  38563. // Shadows
  38564. if (scene.shadowsEnabled) {
  38565. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38566. }
  38567. light._uniformBuffer.update();
  38568. }
  38569. };
  38570. /**
  38571. * Binds the fog information from the scene to the effect for the given mesh.
  38572. * @param scene The scene the lights belongs to
  38573. * @param mesh The mesh we are binding the information to render
  38574. * @param effect The effect we are binding the data to
  38575. */
  38576. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38577. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38578. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38579. effect.setColor3("vFogColor", scene.fogColor);
  38580. }
  38581. };
  38582. /**
  38583. * Binds the bones information from the mesh to the effect.
  38584. * @param mesh The mesh we are binding the information to render
  38585. * @param effect The effect we are binding the data to
  38586. */
  38587. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38588. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38589. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38590. if (matrices && effect) {
  38591. effect.setMatrices("mBones", matrices);
  38592. }
  38593. }
  38594. };
  38595. /**
  38596. * Binds the morph targets information from the mesh to the effect.
  38597. * @param abstractMesh The mesh we are binding the information to render
  38598. * @param effect The effect we are binding the data to
  38599. */
  38600. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38601. var manager = abstractMesh.morphTargetManager;
  38602. if (!abstractMesh || !manager) {
  38603. return;
  38604. }
  38605. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38606. };
  38607. /**
  38608. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38609. * @param defines The generated defines used in the effect
  38610. * @param effect The effect we are binding the data to
  38611. * @param scene The scene we are willing to render with logarithmic scale for
  38612. */
  38613. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38614. if (defines["LOGARITHMICDEPTH"]) {
  38615. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38616. }
  38617. };
  38618. /**
  38619. * Binds the clip plane information from the scene to the effect.
  38620. * @param scene The scene the clip plane information are extracted from
  38621. * @param effect The effect we are binding the data to
  38622. */
  38623. MaterialHelper.BindClipPlane = function (effect, scene) {
  38624. if (scene.clipPlane) {
  38625. var clipPlane = scene.clipPlane;
  38626. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38627. }
  38628. };
  38629. return MaterialHelper;
  38630. }());
  38631. BABYLON.MaterialHelper = MaterialHelper;
  38632. })(BABYLON || (BABYLON = {}));
  38633. //# sourceMappingURL=babylon.materialHelper.js.map
  38634. var BABYLON;
  38635. (function (BABYLON) {
  38636. var PushMaterial = /** @class */ (function (_super) {
  38637. __extends(PushMaterial, _super);
  38638. function PushMaterial(name, scene) {
  38639. var _this = _super.call(this, name, scene) || this;
  38640. _this._normalMatrix = new BABYLON.Matrix();
  38641. _this.storeEffectOnSubMeshes = true;
  38642. return _this;
  38643. }
  38644. PushMaterial.prototype.getEffect = function () {
  38645. return this._activeEffect;
  38646. };
  38647. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38648. if (!mesh) {
  38649. return false;
  38650. }
  38651. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38652. return true;
  38653. }
  38654. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38655. };
  38656. /**
  38657. * Binds the given world matrix to the active effect
  38658. *
  38659. * @param world the matrix to bind
  38660. */
  38661. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38662. this._activeEffect.setMatrix("world", world);
  38663. };
  38664. /**
  38665. * Binds the given normal matrix to the active effect
  38666. *
  38667. * @param normalMatrix the matrix to bind
  38668. */
  38669. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38670. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38671. };
  38672. PushMaterial.prototype.bind = function (world, mesh) {
  38673. if (!mesh) {
  38674. return;
  38675. }
  38676. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38677. };
  38678. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38679. if (effect === void 0) { effect = null; }
  38680. _super.prototype._afterBind.call(this, mesh);
  38681. this.getScene()._cachedEffect = effect;
  38682. };
  38683. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38684. if (visibility === void 0) { visibility = 1; }
  38685. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38686. };
  38687. return PushMaterial;
  38688. }(BABYLON.Material));
  38689. BABYLON.PushMaterial = PushMaterial;
  38690. })(BABYLON || (BABYLON = {}));
  38691. //# sourceMappingURL=babylon.pushMaterial.js.map
  38692. var BABYLON;
  38693. (function (BABYLON) {
  38694. /** @ignore */
  38695. var StandardMaterialDefines = /** @class */ (function (_super) {
  38696. __extends(StandardMaterialDefines, _super);
  38697. function StandardMaterialDefines() {
  38698. var _this = _super.call(this) || this;
  38699. _this.MAINUV1 = false;
  38700. _this.MAINUV2 = false;
  38701. _this.DIFFUSE = false;
  38702. _this.DIFFUSEDIRECTUV = 0;
  38703. _this.AMBIENT = false;
  38704. _this.AMBIENTDIRECTUV = 0;
  38705. _this.OPACITY = false;
  38706. _this.OPACITYDIRECTUV = 0;
  38707. _this.OPACITYRGB = false;
  38708. _this.REFLECTION = false;
  38709. _this.EMISSIVE = false;
  38710. _this.EMISSIVEDIRECTUV = 0;
  38711. _this.SPECULAR = false;
  38712. _this.SPECULARDIRECTUV = 0;
  38713. _this.BUMP = false;
  38714. _this.BUMPDIRECTUV = 0;
  38715. _this.PARALLAX = false;
  38716. _this.PARALLAXOCCLUSION = false;
  38717. _this.SPECULAROVERALPHA = false;
  38718. _this.CLIPPLANE = false;
  38719. _this.ALPHATEST = false;
  38720. _this.DEPTHPREPASS = false;
  38721. _this.ALPHAFROMDIFFUSE = false;
  38722. _this.POINTSIZE = false;
  38723. _this.FOG = false;
  38724. _this.SPECULARTERM = false;
  38725. _this.DIFFUSEFRESNEL = false;
  38726. _this.OPACITYFRESNEL = false;
  38727. _this.REFLECTIONFRESNEL = false;
  38728. _this.REFRACTIONFRESNEL = false;
  38729. _this.EMISSIVEFRESNEL = false;
  38730. _this.FRESNEL = false;
  38731. _this.NORMAL = false;
  38732. _this.UV1 = false;
  38733. _this.UV2 = false;
  38734. _this.VERTEXCOLOR = false;
  38735. _this.VERTEXALPHA = false;
  38736. _this.NUM_BONE_INFLUENCERS = 0;
  38737. _this.BonesPerMesh = 0;
  38738. _this.INSTANCES = false;
  38739. _this.GLOSSINESS = false;
  38740. _this.ROUGHNESS = false;
  38741. _this.EMISSIVEASILLUMINATION = false;
  38742. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38743. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38744. _this.LIGHTMAP = false;
  38745. _this.LIGHTMAPDIRECTUV = 0;
  38746. _this.OBJECTSPACE_NORMALMAP = false;
  38747. _this.USELIGHTMAPASSHADOWMAP = false;
  38748. _this.REFLECTIONMAP_3D = false;
  38749. _this.REFLECTIONMAP_SPHERICAL = false;
  38750. _this.REFLECTIONMAP_PLANAR = false;
  38751. _this.REFLECTIONMAP_CUBIC = false;
  38752. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38753. _this.REFLECTIONMAP_PROJECTION = false;
  38754. _this.REFLECTIONMAP_SKYBOX = false;
  38755. _this.REFLECTIONMAP_EXPLICIT = false;
  38756. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38757. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38758. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38759. _this.INVERTCUBICMAP = false;
  38760. _this.LOGARITHMICDEPTH = false;
  38761. _this.REFRACTION = false;
  38762. _this.REFRACTIONMAP_3D = false;
  38763. _this.REFLECTIONOVERALPHA = false;
  38764. _this.TWOSIDEDLIGHTING = false;
  38765. _this.SHADOWFLOAT = false;
  38766. _this.MORPHTARGETS = false;
  38767. _this.MORPHTARGETS_NORMAL = false;
  38768. _this.MORPHTARGETS_TANGENT = false;
  38769. _this.NUM_MORPH_INFLUENCERS = 0;
  38770. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38771. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38772. _this.IMAGEPROCESSING = false;
  38773. _this.VIGNETTE = false;
  38774. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38775. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38776. _this.TONEMAPPING = false;
  38777. _this.CONTRAST = false;
  38778. _this.COLORCURVES = false;
  38779. _this.COLORGRADING = false;
  38780. _this.COLORGRADING3D = false;
  38781. _this.SAMPLER3DGREENDEPTH = false;
  38782. _this.SAMPLER3DBGRMAP = false;
  38783. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38784. _this.EXPOSURE = false;
  38785. _this.rebuild();
  38786. return _this;
  38787. }
  38788. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38789. var modes = [
  38790. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38791. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38792. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38793. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38794. ];
  38795. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38796. var mode = modes_1[_i];
  38797. this[mode] = (mode === modeToEnable);
  38798. }
  38799. };
  38800. return StandardMaterialDefines;
  38801. }(BABYLON.MaterialDefines));
  38802. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38803. var StandardMaterial = /** @class */ (function (_super) {
  38804. __extends(StandardMaterial, _super);
  38805. function StandardMaterial(name, scene) {
  38806. var _this = _super.call(this, name, scene) || this;
  38807. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38808. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38809. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38810. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38811. _this.specularPower = 64;
  38812. _this._useAlphaFromDiffuseTexture = false;
  38813. _this._useEmissiveAsIllumination = false;
  38814. _this._linkEmissiveWithDiffuse = false;
  38815. _this._useSpecularOverAlpha = false;
  38816. _this._useReflectionOverAlpha = false;
  38817. _this._disableLighting = false;
  38818. _this._useObjectSpaceNormalMap = false;
  38819. _this._useParallax = false;
  38820. _this._useParallaxOcclusion = false;
  38821. _this.parallaxScaleBias = 0.05;
  38822. _this._roughness = 0;
  38823. _this.indexOfRefraction = 0.98;
  38824. _this.invertRefractionY = true;
  38825. _this._useLightmapAsShadowmap = false;
  38826. _this._useReflectionFresnelFromSpecular = false;
  38827. _this._useGlossinessFromSpecularMapAlpha = false;
  38828. _this._maxSimultaneousLights = 4;
  38829. /**
  38830. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38831. */
  38832. _this._invertNormalMapX = false;
  38833. /**
  38834. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38835. */
  38836. _this._invertNormalMapY = false;
  38837. /**
  38838. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38839. */
  38840. _this._twoSidedLighting = false;
  38841. _this._renderTargets = new BABYLON.SmartArray(16);
  38842. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38843. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38844. // Setup the default processing configuration to the scene.
  38845. _this._attachImageProcessingConfiguration(null);
  38846. _this.getRenderTargetTextures = function () {
  38847. _this._renderTargets.reset();
  38848. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38849. _this._renderTargets.push(_this._reflectionTexture);
  38850. }
  38851. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38852. _this._renderTargets.push(_this._refractionTexture);
  38853. }
  38854. return _this._renderTargets;
  38855. };
  38856. return _this;
  38857. }
  38858. ;
  38859. ;
  38860. ;
  38861. ;
  38862. ;
  38863. ;
  38864. ;
  38865. ;
  38866. ;
  38867. ;
  38868. ;
  38869. ;
  38870. ;
  38871. ;
  38872. ;
  38873. ;
  38874. ;
  38875. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38876. /**
  38877. * Gets the image processing configuration used either in this material.
  38878. */
  38879. get: function () {
  38880. return this._imageProcessingConfiguration;
  38881. },
  38882. /**
  38883. * Sets the Default image processing configuration used either in the this material.
  38884. *
  38885. * If sets to null, the scene one is in use.
  38886. */
  38887. set: function (value) {
  38888. this._attachImageProcessingConfiguration(value);
  38889. // Ensure the effect will be rebuilt.
  38890. this._markAllSubMeshesAsTexturesDirty();
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. /**
  38896. * Attaches a new image processing configuration to the Standard Material.
  38897. * @param configuration
  38898. */
  38899. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38900. var _this = this;
  38901. if (configuration === this._imageProcessingConfiguration) {
  38902. return;
  38903. }
  38904. // Detaches observer.
  38905. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38906. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38907. }
  38908. // Pick the scene configuration if needed.
  38909. if (!configuration) {
  38910. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38911. }
  38912. else {
  38913. this._imageProcessingConfiguration = configuration;
  38914. }
  38915. // Attaches observer.
  38916. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38917. _this._markAllSubMeshesAsImageProcessingDirty();
  38918. });
  38919. };
  38920. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38921. /**
  38922. * Gets wether the color curves effect is enabled.
  38923. */
  38924. get: function () {
  38925. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38926. },
  38927. /**
  38928. * Sets wether the color curves effect is enabled.
  38929. */
  38930. set: function (value) {
  38931. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38932. },
  38933. enumerable: true,
  38934. configurable: true
  38935. });
  38936. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38937. /**
  38938. * Gets wether the color grading effect is enabled.
  38939. */
  38940. get: function () {
  38941. return this.imageProcessingConfiguration.colorGradingEnabled;
  38942. },
  38943. /**
  38944. * Gets wether the color grading effect is enabled.
  38945. */
  38946. set: function (value) {
  38947. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38948. },
  38949. enumerable: true,
  38950. configurable: true
  38951. });
  38952. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38953. /**
  38954. * Gets wether tonemapping is enabled or not.
  38955. */
  38956. get: function () {
  38957. return this._imageProcessingConfiguration.toneMappingEnabled;
  38958. },
  38959. /**
  38960. * Sets wether tonemapping is enabled or not
  38961. */
  38962. set: function (value) {
  38963. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38964. },
  38965. enumerable: true,
  38966. configurable: true
  38967. });
  38968. ;
  38969. ;
  38970. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38971. /**
  38972. * The camera exposure used on this material.
  38973. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38974. * This corresponds to a photographic exposure.
  38975. */
  38976. get: function () {
  38977. return this._imageProcessingConfiguration.exposure;
  38978. },
  38979. /**
  38980. * The camera exposure used on this material.
  38981. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38982. * This corresponds to a photographic exposure.
  38983. */
  38984. set: function (value) {
  38985. this._imageProcessingConfiguration.exposure = value;
  38986. },
  38987. enumerable: true,
  38988. configurable: true
  38989. });
  38990. ;
  38991. ;
  38992. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38993. /**
  38994. * Gets The camera contrast used on this material.
  38995. */
  38996. get: function () {
  38997. return this._imageProcessingConfiguration.contrast;
  38998. },
  38999. /**
  39000. * Sets The camera contrast used on this material.
  39001. */
  39002. set: function (value) {
  39003. this._imageProcessingConfiguration.contrast = value;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39009. /**
  39010. * Gets the Color Grading 2D Lookup Texture.
  39011. */
  39012. get: function () {
  39013. return this._imageProcessingConfiguration.colorGradingTexture;
  39014. },
  39015. /**
  39016. * Sets the Color Grading 2D Lookup Texture.
  39017. */
  39018. set: function (value) {
  39019. this._imageProcessingConfiguration.colorGradingTexture = value;
  39020. },
  39021. enumerable: true,
  39022. configurable: true
  39023. });
  39024. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39025. /**
  39026. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39027. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39028. * 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;
  39029. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39030. */
  39031. get: function () {
  39032. return this._imageProcessingConfiguration.colorCurves;
  39033. },
  39034. /**
  39035. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39036. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39037. * 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;
  39038. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39039. */
  39040. set: function (value) {
  39041. this._imageProcessingConfiguration.colorCurves = value;
  39042. },
  39043. enumerable: true,
  39044. configurable: true
  39045. });
  39046. StandardMaterial.prototype.getClassName = function () {
  39047. return "StandardMaterial";
  39048. };
  39049. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39050. get: function () {
  39051. return this._useLogarithmicDepth;
  39052. },
  39053. set: function (value) {
  39054. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39055. this._markAllSubMeshesAsMiscDirty();
  39056. },
  39057. enumerable: true,
  39058. configurable: true
  39059. });
  39060. StandardMaterial.prototype.needAlphaBlending = function () {
  39061. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39062. };
  39063. StandardMaterial.prototype.needAlphaTesting = function () {
  39064. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39065. };
  39066. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39067. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39068. };
  39069. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39070. return this._diffuseTexture;
  39071. };
  39072. /**
  39073. * Child classes can use it to update shaders
  39074. */
  39075. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39076. if (useInstances === void 0) { useInstances = false; }
  39077. if (subMesh.effect && this.isFrozen) {
  39078. if (this._wasPreviouslyReady && subMesh.effect) {
  39079. return true;
  39080. }
  39081. }
  39082. if (!subMesh._materialDefines) {
  39083. subMesh._materialDefines = new StandardMaterialDefines();
  39084. }
  39085. var scene = this.getScene();
  39086. var defines = subMesh._materialDefines;
  39087. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39088. if (defines._renderId === scene.getRenderId()) {
  39089. return true;
  39090. }
  39091. }
  39092. var engine = scene.getEngine();
  39093. // Lights
  39094. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39095. // Textures
  39096. if (defines._areTexturesDirty) {
  39097. defines._needUVs = false;
  39098. defines.MAINUV1 = false;
  39099. defines.MAINUV2 = false;
  39100. if (scene.texturesEnabled) {
  39101. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39102. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39103. return false;
  39104. }
  39105. else {
  39106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39107. }
  39108. }
  39109. else {
  39110. defines.DIFFUSE = false;
  39111. }
  39112. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39113. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39114. return false;
  39115. }
  39116. else {
  39117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39118. }
  39119. }
  39120. else {
  39121. defines.AMBIENT = false;
  39122. }
  39123. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39124. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39125. return false;
  39126. }
  39127. else {
  39128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39129. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39130. }
  39131. }
  39132. else {
  39133. defines.OPACITY = false;
  39134. }
  39135. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39136. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39137. return false;
  39138. }
  39139. else {
  39140. defines._needNormals = true;
  39141. defines.REFLECTION = true;
  39142. defines.ROUGHNESS = (this._roughness > 0);
  39143. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39144. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39145. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39146. switch (this._reflectionTexture.coordinatesMode) {
  39147. case BABYLON.Texture.CUBIC_MODE:
  39148. case BABYLON.Texture.INVCUBIC_MODE:
  39149. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39150. break;
  39151. case BABYLON.Texture.EXPLICIT_MODE:
  39152. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39153. break;
  39154. case BABYLON.Texture.PLANAR_MODE:
  39155. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39156. break;
  39157. case BABYLON.Texture.PROJECTION_MODE:
  39158. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39159. break;
  39160. case BABYLON.Texture.SKYBOX_MODE:
  39161. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39162. break;
  39163. case BABYLON.Texture.SPHERICAL_MODE:
  39164. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39165. break;
  39166. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39167. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39168. break;
  39169. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39170. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39171. break;
  39172. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39173. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39174. break;
  39175. }
  39176. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39177. }
  39178. }
  39179. else {
  39180. defines.REFLECTION = false;
  39181. }
  39182. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39183. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39184. return false;
  39185. }
  39186. else {
  39187. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39188. }
  39189. }
  39190. else {
  39191. defines.EMISSIVE = false;
  39192. }
  39193. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39194. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39195. return false;
  39196. }
  39197. else {
  39198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39199. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39200. }
  39201. }
  39202. else {
  39203. defines.LIGHTMAP = false;
  39204. }
  39205. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39206. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39207. return false;
  39208. }
  39209. else {
  39210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39211. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39212. }
  39213. }
  39214. else {
  39215. defines.SPECULAR = false;
  39216. }
  39217. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39218. // Bump texure can not be not blocking.
  39219. if (!this._bumpTexture.isReady()) {
  39220. return false;
  39221. }
  39222. else {
  39223. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39224. defines.PARALLAX = this._useParallax;
  39225. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39226. }
  39227. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39228. }
  39229. else {
  39230. defines.BUMP = false;
  39231. }
  39232. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39233. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39234. return false;
  39235. }
  39236. else {
  39237. defines._needUVs = true;
  39238. defines.REFRACTION = true;
  39239. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39240. }
  39241. }
  39242. else {
  39243. defines.REFRACTION = false;
  39244. }
  39245. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39246. }
  39247. else {
  39248. defines.DIFFUSE = false;
  39249. defines.AMBIENT = false;
  39250. defines.OPACITY = false;
  39251. defines.REFLECTION = false;
  39252. defines.EMISSIVE = false;
  39253. defines.LIGHTMAP = false;
  39254. defines.BUMP = false;
  39255. defines.REFRACTION = false;
  39256. }
  39257. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39258. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39259. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39260. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39261. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39262. }
  39263. if (defines._areImageProcessingDirty) {
  39264. if (!this._imageProcessingConfiguration.isReady()) {
  39265. return false;
  39266. }
  39267. this._imageProcessingConfiguration.prepareDefines(defines);
  39268. }
  39269. if (defines._areFresnelDirty) {
  39270. if (StandardMaterial.FresnelEnabled) {
  39271. // Fresnel
  39272. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39273. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39274. this._reflectionFresnelParameters) {
  39275. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39276. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39277. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39278. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39279. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39280. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39281. defines._needNormals = true;
  39282. defines.FRESNEL = true;
  39283. }
  39284. }
  39285. else {
  39286. defines.FRESNEL = false;
  39287. }
  39288. }
  39289. // Misc.
  39290. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39291. // Attribs
  39292. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39293. // Values that need to be evaluated on every frame
  39294. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39295. // Get correct effect
  39296. if (defines.isDirty) {
  39297. defines.markAsProcessed();
  39298. scene.resetCachedMaterial();
  39299. // Fallbacks
  39300. var fallbacks = new BABYLON.EffectFallbacks();
  39301. if (defines.REFLECTION) {
  39302. fallbacks.addFallback(0, "REFLECTION");
  39303. }
  39304. if (defines.SPECULAR) {
  39305. fallbacks.addFallback(0, "SPECULAR");
  39306. }
  39307. if (defines.BUMP) {
  39308. fallbacks.addFallback(0, "BUMP");
  39309. }
  39310. if (defines.PARALLAX) {
  39311. fallbacks.addFallback(1, "PARALLAX");
  39312. }
  39313. if (defines.PARALLAXOCCLUSION) {
  39314. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39315. }
  39316. if (defines.SPECULAROVERALPHA) {
  39317. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39318. }
  39319. if (defines.FOG) {
  39320. fallbacks.addFallback(1, "FOG");
  39321. }
  39322. if (defines.POINTSIZE) {
  39323. fallbacks.addFallback(0, "POINTSIZE");
  39324. }
  39325. if (defines.LOGARITHMICDEPTH) {
  39326. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39327. }
  39328. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39329. if (defines.SPECULARTERM) {
  39330. fallbacks.addFallback(0, "SPECULARTERM");
  39331. }
  39332. if (defines.DIFFUSEFRESNEL) {
  39333. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39334. }
  39335. if (defines.OPACITYFRESNEL) {
  39336. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39337. }
  39338. if (defines.REFLECTIONFRESNEL) {
  39339. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39340. }
  39341. if (defines.EMISSIVEFRESNEL) {
  39342. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39343. }
  39344. if (defines.FRESNEL) {
  39345. fallbacks.addFallback(4, "FRESNEL");
  39346. }
  39347. //Attributes
  39348. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39349. if (defines.NORMAL) {
  39350. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39351. }
  39352. if (defines.UV1) {
  39353. attribs.push(BABYLON.VertexBuffer.UVKind);
  39354. }
  39355. if (defines.UV2) {
  39356. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39357. }
  39358. if (defines.VERTEXCOLOR) {
  39359. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39360. }
  39361. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39362. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39363. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39364. var shaderName = "default";
  39365. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39366. "vFogInfos", "vFogColor", "pointSize",
  39367. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39368. "mBones",
  39369. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39370. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39371. "vReflectionPosition", "vReflectionSize",
  39372. "logarithmicDepthConstant", "vTangentSpaceParams"
  39373. ];
  39374. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39375. var uniformBuffers = ["Material", "Scene"];
  39376. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39377. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39378. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39379. uniformsNames: uniforms,
  39380. uniformBuffersNames: uniformBuffers,
  39381. samplers: samplers,
  39382. defines: defines,
  39383. maxSimultaneousLights: this._maxSimultaneousLights
  39384. });
  39385. if (this.customShaderNameResolve) {
  39386. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39387. }
  39388. var join = defines.toString();
  39389. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39390. attributes: attribs,
  39391. uniformsNames: uniforms,
  39392. uniformBuffersNames: uniformBuffers,
  39393. samplers: samplers,
  39394. defines: join,
  39395. fallbacks: fallbacks,
  39396. onCompiled: this.onCompiled,
  39397. onError: this.onError,
  39398. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39399. }, engine), defines);
  39400. this.buildUniformLayout();
  39401. }
  39402. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39403. return false;
  39404. }
  39405. defines._renderId = scene.getRenderId();
  39406. this._wasPreviouslyReady = true;
  39407. return true;
  39408. };
  39409. StandardMaterial.prototype.buildUniformLayout = function () {
  39410. // Order is important !
  39411. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39412. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39413. this._uniformBuffer.addUniform("opacityParts", 4);
  39414. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39415. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39416. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39417. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39418. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39419. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39420. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39421. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39422. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39423. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39424. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39425. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39426. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39427. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39428. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39429. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39430. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39431. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39432. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39433. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39434. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39435. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39436. this._uniformBuffer.addUniform("specularMatrix", 16);
  39437. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39438. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39439. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39440. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39441. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39442. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39443. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39444. this._uniformBuffer.addUniform("pointSize", 1);
  39445. this._uniformBuffer.create();
  39446. };
  39447. StandardMaterial.prototype.unbind = function () {
  39448. if (this._activeEffect) {
  39449. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39450. this._activeEffect.setTexture("reflection2DSampler", null);
  39451. }
  39452. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39453. this._activeEffect.setTexture("refraction2DSampler", null);
  39454. }
  39455. }
  39456. _super.prototype.unbind.call(this);
  39457. };
  39458. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39459. var scene = this.getScene();
  39460. var defines = subMesh._materialDefines;
  39461. if (!defines) {
  39462. return;
  39463. }
  39464. var effect = subMesh.effect;
  39465. if (!effect) {
  39466. return;
  39467. }
  39468. this._activeEffect = effect;
  39469. // Matrices
  39470. this.bindOnlyWorldMatrix(world);
  39471. // Normal Matrix
  39472. if (defines.OBJECTSPACE_NORMALMAP) {
  39473. world.toNormalMatrix(this._normalMatrix);
  39474. this.bindOnlyNormalMatrix(this._normalMatrix);
  39475. }
  39476. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39477. // Bones
  39478. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39479. if (mustRebind) {
  39480. this._uniformBuffer.bindToEffect(effect, "Material");
  39481. this.bindViewProjection(effect);
  39482. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39483. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39484. // Fresnel
  39485. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39486. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39487. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39488. }
  39489. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39490. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39491. }
  39492. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39493. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39494. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39495. }
  39496. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39497. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39498. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39499. }
  39500. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39501. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39502. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39503. }
  39504. }
  39505. // Textures
  39506. if (scene.texturesEnabled) {
  39507. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39508. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39509. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39510. }
  39511. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39512. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39513. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39514. }
  39515. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39516. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39517. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39518. }
  39519. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39520. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39521. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39522. if (this._reflectionTexture.boundingBoxSize) {
  39523. var cubeTexture = this._reflectionTexture;
  39524. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39525. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39526. }
  39527. }
  39528. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39529. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39530. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39531. }
  39532. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39533. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39534. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39535. }
  39536. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39537. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39538. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39539. }
  39540. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39541. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39542. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39543. if (scene._mirroredCameraPosition) {
  39544. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39545. }
  39546. else {
  39547. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39548. }
  39549. }
  39550. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39551. var depth = 1.0;
  39552. if (!this._refractionTexture.isCube) {
  39553. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39554. if (this._refractionTexture.depth) {
  39555. depth = this._refractionTexture.depth;
  39556. }
  39557. }
  39558. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39559. }
  39560. }
  39561. // Point size
  39562. if (this.pointsCloud) {
  39563. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39564. }
  39565. if (defines.SPECULARTERM) {
  39566. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39567. }
  39568. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39569. // Diffuse
  39570. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39571. }
  39572. // Textures
  39573. if (scene.texturesEnabled) {
  39574. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39575. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39576. }
  39577. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39578. effect.setTexture("ambientSampler", this._ambientTexture);
  39579. }
  39580. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39581. effect.setTexture("opacitySampler", this._opacityTexture);
  39582. }
  39583. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39584. if (this._reflectionTexture.isCube) {
  39585. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39586. }
  39587. else {
  39588. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39589. }
  39590. }
  39591. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39592. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39593. }
  39594. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39595. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39596. }
  39597. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39598. effect.setTexture("specularSampler", this._specularTexture);
  39599. }
  39600. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39601. effect.setTexture("bumpSampler", this._bumpTexture);
  39602. }
  39603. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39604. var depth = 1.0;
  39605. if (this._refractionTexture.isCube) {
  39606. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39607. }
  39608. else {
  39609. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39610. }
  39611. }
  39612. }
  39613. // Clip plane
  39614. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39615. // Colors
  39616. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39617. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39618. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39619. }
  39620. if (mustRebind || !this.isFrozen) {
  39621. // Lights
  39622. if (scene.lightsEnabled && !this._disableLighting) {
  39623. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39624. }
  39625. // View
  39626. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39627. this.bindView(effect);
  39628. }
  39629. // Fog
  39630. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39631. // Morph targets
  39632. if (defines.NUM_MORPH_INFLUENCERS) {
  39633. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39634. }
  39635. // Log. depth
  39636. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39637. // image processing
  39638. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39639. this._imageProcessingConfiguration.bind(this._activeEffect);
  39640. }
  39641. }
  39642. this._uniformBuffer.update();
  39643. this._afterBind(mesh, this._activeEffect);
  39644. };
  39645. StandardMaterial.prototype.getAnimatables = function () {
  39646. var results = [];
  39647. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39648. results.push(this._diffuseTexture);
  39649. }
  39650. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39651. results.push(this._ambientTexture);
  39652. }
  39653. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39654. results.push(this._opacityTexture);
  39655. }
  39656. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39657. results.push(this._reflectionTexture);
  39658. }
  39659. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39660. results.push(this._emissiveTexture);
  39661. }
  39662. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39663. results.push(this._specularTexture);
  39664. }
  39665. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39666. results.push(this._bumpTexture);
  39667. }
  39668. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39669. results.push(this._lightmapTexture);
  39670. }
  39671. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39672. results.push(this._refractionTexture);
  39673. }
  39674. return results;
  39675. };
  39676. StandardMaterial.prototype.getActiveTextures = function () {
  39677. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39678. if (this._diffuseTexture) {
  39679. activeTextures.push(this._diffuseTexture);
  39680. }
  39681. if (this._ambientTexture) {
  39682. activeTextures.push(this._ambientTexture);
  39683. }
  39684. if (this._opacityTexture) {
  39685. activeTextures.push(this._opacityTexture);
  39686. }
  39687. if (this._reflectionTexture) {
  39688. activeTextures.push(this._reflectionTexture);
  39689. }
  39690. if (this._emissiveTexture) {
  39691. activeTextures.push(this._emissiveTexture);
  39692. }
  39693. if (this._specularTexture) {
  39694. activeTextures.push(this._specularTexture);
  39695. }
  39696. if (this._bumpTexture) {
  39697. activeTextures.push(this._bumpTexture);
  39698. }
  39699. if (this._lightmapTexture) {
  39700. activeTextures.push(this._lightmapTexture);
  39701. }
  39702. if (this._refractionTexture) {
  39703. activeTextures.push(this._refractionTexture);
  39704. }
  39705. return activeTextures;
  39706. };
  39707. StandardMaterial.prototype.hasTexture = function (texture) {
  39708. if (_super.prototype.hasTexture.call(this, texture)) {
  39709. return true;
  39710. }
  39711. if (this._diffuseTexture === texture) {
  39712. return true;
  39713. }
  39714. if (this._ambientTexture === texture) {
  39715. return true;
  39716. }
  39717. if (this._opacityTexture === texture) {
  39718. return true;
  39719. }
  39720. if (this._reflectionTexture === texture) {
  39721. return true;
  39722. }
  39723. if (this._emissiveTexture === texture) {
  39724. return true;
  39725. }
  39726. if (this._specularTexture === texture) {
  39727. return true;
  39728. }
  39729. if (this._bumpTexture === texture) {
  39730. return true;
  39731. }
  39732. if (this._lightmapTexture === texture) {
  39733. return true;
  39734. }
  39735. if (this._refractionTexture === texture) {
  39736. return true;
  39737. }
  39738. return false;
  39739. };
  39740. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39741. if (forceDisposeTextures) {
  39742. if (this._diffuseTexture) {
  39743. this._diffuseTexture.dispose();
  39744. }
  39745. if (this._ambientTexture) {
  39746. this._ambientTexture.dispose();
  39747. }
  39748. if (this._opacityTexture) {
  39749. this._opacityTexture.dispose();
  39750. }
  39751. if (this._reflectionTexture) {
  39752. this._reflectionTexture.dispose();
  39753. }
  39754. if (this._emissiveTexture) {
  39755. this._emissiveTexture.dispose();
  39756. }
  39757. if (this._specularTexture) {
  39758. this._specularTexture.dispose();
  39759. }
  39760. if (this._bumpTexture) {
  39761. this._bumpTexture.dispose();
  39762. }
  39763. if (this._lightmapTexture) {
  39764. this._lightmapTexture.dispose();
  39765. }
  39766. if (this._refractionTexture) {
  39767. this._refractionTexture.dispose();
  39768. }
  39769. }
  39770. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39771. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39772. }
  39773. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39774. };
  39775. StandardMaterial.prototype.clone = function (name) {
  39776. var _this = this;
  39777. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39778. result.name = name;
  39779. result.id = name;
  39780. return result;
  39781. };
  39782. StandardMaterial.prototype.serialize = function () {
  39783. return BABYLON.SerializationHelper.Serialize(this);
  39784. };
  39785. // Statics
  39786. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39787. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39788. };
  39789. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39790. get: function () {
  39791. return StandardMaterial._DiffuseTextureEnabled;
  39792. },
  39793. set: function (value) {
  39794. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39795. return;
  39796. }
  39797. StandardMaterial._DiffuseTextureEnabled = value;
  39798. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39799. },
  39800. enumerable: true,
  39801. configurable: true
  39802. });
  39803. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39804. get: function () {
  39805. return StandardMaterial._AmbientTextureEnabled;
  39806. },
  39807. set: function (value) {
  39808. if (StandardMaterial._AmbientTextureEnabled === value) {
  39809. return;
  39810. }
  39811. StandardMaterial._AmbientTextureEnabled = value;
  39812. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39818. get: function () {
  39819. return StandardMaterial._OpacityTextureEnabled;
  39820. },
  39821. set: function (value) {
  39822. if (StandardMaterial._OpacityTextureEnabled === value) {
  39823. return;
  39824. }
  39825. StandardMaterial._OpacityTextureEnabled = value;
  39826. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39832. get: function () {
  39833. return StandardMaterial._ReflectionTextureEnabled;
  39834. },
  39835. set: function (value) {
  39836. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39837. return;
  39838. }
  39839. StandardMaterial._ReflectionTextureEnabled = value;
  39840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39841. },
  39842. enumerable: true,
  39843. configurable: true
  39844. });
  39845. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39846. get: function () {
  39847. return StandardMaterial._EmissiveTextureEnabled;
  39848. },
  39849. set: function (value) {
  39850. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39851. return;
  39852. }
  39853. StandardMaterial._EmissiveTextureEnabled = value;
  39854. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39855. },
  39856. enumerable: true,
  39857. configurable: true
  39858. });
  39859. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39860. get: function () {
  39861. return StandardMaterial._SpecularTextureEnabled;
  39862. },
  39863. set: function (value) {
  39864. if (StandardMaterial._SpecularTextureEnabled === value) {
  39865. return;
  39866. }
  39867. StandardMaterial._SpecularTextureEnabled = value;
  39868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39874. get: function () {
  39875. return StandardMaterial._BumpTextureEnabled;
  39876. },
  39877. set: function (value) {
  39878. if (StandardMaterial._BumpTextureEnabled === value) {
  39879. return;
  39880. }
  39881. StandardMaterial._BumpTextureEnabled = value;
  39882. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39888. get: function () {
  39889. return StandardMaterial._LightmapTextureEnabled;
  39890. },
  39891. set: function (value) {
  39892. if (StandardMaterial._LightmapTextureEnabled === value) {
  39893. return;
  39894. }
  39895. StandardMaterial._LightmapTextureEnabled = value;
  39896. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39902. get: function () {
  39903. return StandardMaterial._RefractionTextureEnabled;
  39904. },
  39905. set: function (value) {
  39906. if (StandardMaterial._RefractionTextureEnabled === value) {
  39907. return;
  39908. }
  39909. StandardMaterial._RefractionTextureEnabled = value;
  39910. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39911. },
  39912. enumerable: true,
  39913. configurable: true
  39914. });
  39915. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39916. get: function () {
  39917. return StandardMaterial._ColorGradingTextureEnabled;
  39918. },
  39919. set: function (value) {
  39920. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39921. return;
  39922. }
  39923. StandardMaterial._ColorGradingTextureEnabled = value;
  39924. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39925. },
  39926. enumerable: true,
  39927. configurable: true
  39928. });
  39929. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39930. get: function () {
  39931. return StandardMaterial._FresnelEnabled;
  39932. },
  39933. set: function (value) {
  39934. if (StandardMaterial._FresnelEnabled === value) {
  39935. return;
  39936. }
  39937. StandardMaterial._FresnelEnabled = value;
  39938. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39939. },
  39940. enumerable: true,
  39941. configurable: true
  39942. });
  39943. // Flags used to enable or disable a type of texture for all Standard Materials
  39944. StandardMaterial._DiffuseTextureEnabled = true;
  39945. StandardMaterial._AmbientTextureEnabled = true;
  39946. StandardMaterial._OpacityTextureEnabled = true;
  39947. StandardMaterial._ReflectionTextureEnabled = true;
  39948. StandardMaterial._EmissiveTextureEnabled = true;
  39949. StandardMaterial._SpecularTextureEnabled = true;
  39950. StandardMaterial._BumpTextureEnabled = true;
  39951. StandardMaterial._LightmapTextureEnabled = true;
  39952. StandardMaterial._RefractionTextureEnabled = true;
  39953. StandardMaterial._ColorGradingTextureEnabled = true;
  39954. StandardMaterial._FresnelEnabled = true;
  39955. __decorate([
  39956. BABYLON.serializeAsTexture("diffuseTexture")
  39957. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39958. __decorate([
  39959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39960. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39961. __decorate([
  39962. BABYLON.serializeAsTexture("ambientTexture")
  39963. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39964. __decorate([
  39965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39966. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39967. __decorate([
  39968. BABYLON.serializeAsTexture("opacityTexture")
  39969. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39970. __decorate([
  39971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39972. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39973. __decorate([
  39974. BABYLON.serializeAsTexture("reflectionTexture")
  39975. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39976. __decorate([
  39977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39978. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39979. __decorate([
  39980. BABYLON.serializeAsTexture("emissiveTexture")
  39981. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39982. __decorate([
  39983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39984. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39985. __decorate([
  39986. BABYLON.serializeAsTexture("specularTexture")
  39987. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39988. __decorate([
  39989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39990. ], StandardMaterial.prototype, "specularTexture", void 0);
  39991. __decorate([
  39992. BABYLON.serializeAsTexture("bumpTexture")
  39993. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39994. __decorate([
  39995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39996. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39997. __decorate([
  39998. BABYLON.serializeAsTexture("lightmapTexture")
  39999. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40000. __decorate([
  40001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40002. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40003. __decorate([
  40004. BABYLON.serializeAsTexture("refractionTexture")
  40005. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40006. __decorate([
  40007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40008. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40009. __decorate([
  40010. BABYLON.serializeAsColor3("ambient")
  40011. ], StandardMaterial.prototype, "ambientColor", void 0);
  40012. __decorate([
  40013. BABYLON.serializeAsColor3("diffuse")
  40014. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40015. __decorate([
  40016. BABYLON.serializeAsColor3("specular")
  40017. ], StandardMaterial.prototype, "specularColor", void 0);
  40018. __decorate([
  40019. BABYLON.serializeAsColor3("emissive")
  40020. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40021. __decorate([
  40022. BABYLON.serialize()
  40023. ], StandardMaterial.prototype, "specularPower", void 0);
  40024. __decorate([
  40025. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40026. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40027. __decorate([
  40028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40029. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40030. __decorate([
  40031. BABYLON.serialize("useEmissiveAsIllumination")
  40032. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40033. __decorate([
  40034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40035. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40036. __decorate([
  40037. BABYLON.serialize("linkEmissiveWithDiffuse")
  40038. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40039. __decorate([
  40040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40041. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40042. __decorate([
  40043. BABYLON.serialize("useSpecularOverAlpha")
  40044. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40045. __decorate([
  40046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40047. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40048. __decorate([
  40049. BABYLON.serialize("useReflectionOverAlpha")
  40050. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40051. __decorate([
  40052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40053. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40054. __decorate([
  40055. BABYLON.serialize("disableLighting")
  40056. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40057. __decorate([
  40058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40059. ], StandardMaterial.prototype, "disableLighting", void 0);
  40060. __decorate([
  40061. BABYLON.serialize("useObjectSpaceNormalMap")
  40062. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40063. __decorate([
  40064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40065. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40066. __decorate([
  40067. BABYLON.serialize("useParallax")
  40068. ], StandardMaterial.prototype, "_useParallax", void 0);
  40069. __decorate([
  40070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40071. ], StandardMaterial.prototype, "useParallax", void 0);
  40072. __decorate([
  40073. BABYLON.serialize("useParallaxOcclusion")
  40074. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40075. __decorate([
  40076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40077. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40078. __decorate([
  40079. BABYLON.serialize()
  40080. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40081. __decorate([
  40082. BABYLON.serialize("roughness")
  40083. ], StandardMaterial.prototype, "_roughness", void 0);
  40084. __decorate([
  40085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40086. ], StandardMaterial.prototype, "roughness", void 0);
  40087. __decorate([
  40088. BABYLON.serialize()
  40089. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40090. __decorate([
  40091. BABYLON.serialize()
  40092. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40093. __decorate([
  40094. BABYLON.serialize("useLightmapAsShadowmap")
  40095. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40096. __decorate([
  40097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40098. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40099. __decorate([
  40100. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40101. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40102. __decorate([
  40103. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40104. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40105. __decorate([
  40106. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40107. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40108. __decorate([
  40109. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40110. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40111. __decorate([
  40112. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40113. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40114. __decorate([
  40115. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40116. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40117. __decorate([
  40118. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40119. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40120. __decorate([
  40121. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40122. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40123. __decorate([
  40124. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40125. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40126. __decorate([
  40127. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40128. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40129. __decorate([
  40130. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40131. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40132. __decorate([
  40133. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40134. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40135. __decorate([
  40136. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40137. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40138. __decorate([
  40139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40140. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40141. __decorate([
  40142. BABYLON.serialize("maxSimultaneousLights")
  40143. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40144. __decorate([
  40145. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40146. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40147. __decorate([
  40148. BABYLON.serialize("invertNormalMapX")
  40149. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40150. __decorate([
  40151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40152. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40153. __decorate([
  40154. BABYLON.serialize("invertNormalMapY")
  40155. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40156. __decorate([
  40157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40158. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40159. __decorate([
  40160. BABYLON.serialize("twoSidedLighting")
  40161. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40162. __decorate([
  40163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40164. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40165. __decorate([
  40166. BABYLON.serialize()
  40167. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40168. return StandardMaterial;
  40169. }(BABYLON.PushMaterial));
  40170. BABYLON.StandardMaterial = StandardMaterial;
  40171. })(BABYLON || (BABYLON = {}));
  40172. //# sourceMappingURL=babylon.standardMaterial.js.map
  40173. var BABYLON;
  40174. (function (BABYLON) {
  40175. /**
  40176. * Manages the defines for the PBR Material.
  40177. */
  40178. var PBRMaterialDefines = /** @class */ (function (_super) {
  40179. __extends(PBRMaterialDefines, _super);
  40180. /**
  40181. * Initializes the PBR Material defines.
  40182. */
  40183. function PBRMaterialDefines() {
  40184. var _this = _super.call(this) || this;
  40185. _this.PBR = true;
  40186. _this.MAINUV1 = false;
  40187. _this.MAINUV2 = false;
  40188. _this.UV1 = false;
  40189. _this.UV2 = false;
  40190. _this.ALBEDO = false;
  40191. _this.ALBEDODIRECTUV = 0;
  40192. _this.VERTEXCOLOR = false;
  40193. _this.AMBIENT = false;
  40194. _this.AMBIENTDIRECTUV = 0;
  40195. _this.AMBIENTINGRAYSCALE = false;
  40196. _this.OPACITY = false;
  40197. _this.VERTEXALPHA = false;
  40198. _this.OPACITYDIRECTUV = 0;
  40199. _this.OPACITYRGB = false;
  40200. _this.ALPHATEST = false;
  40201. _this.DEPTHPREPASS = false;
  40202. _this.ALPHABLEND = false;
  40203. _this.ALPHAFROMALBEDO = false;
  40204. _this.ALPHATESTVALUE = 0.5;
  40205. _this.SPECULAROVERALPHA = false;
  40206. _this.RADIANCEOVERALPHA = false;
  40207. _this.ALPHAFRESNEL = false;
  40208. _this.LINEARALPHAFRESNEL = false;
  40209. _this.PREMULTIPLYALPHA = false;
  40210. _this.EMISSIVE = false;
  40211. _this.EMISSIVEDIRECTUV = 0;
  40212. _this.REFLECTIVITY = false;
  40213. _this.REFLECTIVITYDIRECTUV = 0;
  40214. _this.SPECULARTERM = false;
  40215. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40216. _this.MICROSURFACEAUTOMATIC = false;
  40217. _this.LODBASEDMICROSFURACE = false;
  40218. _this.MICROSURFACEMAP = false;
  40219. _this.MICROSURFACEMAPDIRECTUV = 0;
  40220. _this.METALLICWORKFLOW = false;
  40221. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40222. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40223. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40224. _this.AOSTOREINMETALMAPRED = false;
  40225. _this.ENVIRONMENTBRDF = false;
  40226. _this.NORMAL = false;
  40227. _this.TANGENT = false;
  40228. _this.BUMP = false;
  40229. _this.BUMPDIRECTUV = 0;
  40230. _this.OBJECTSPACE_NORMALMAP = false;
  40231. _this.PARALLAX = false;
  40232. _this.PARALLAXOCCLUSION = false;
  40233. _this.NORMALXYSCALE = true;
  40234. _this.LIGHTMAP = false;
  40235. _this.LIGHTMAPDIRECTUV = 0;
  40236. _this.USELIGHTMAPASSHADOWMAP = false;
  40237. _this.REFLECTION = false;
  40238. _this.REFLECTIONMAP_3D = false;
  40239. _this.REFLECTIONMAP_SPHERICAL = false;
  40240. _this.REFLECTIONMAP_PLANAR = false;
  40241. _this.REFLECTIONMAP_CUBIC = false;
  40242. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40243. _this.REFLECTIONMAP_PROJECTION = false;
  40244. _this.REFLECTIONMAP_SKYBOX = false;
  40245. _this.REFLECTIONMAP_EXPLICIT = false;
  40246. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40247. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40248. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40249. _this.INVERTCUBICMAP = false;
  40250. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40251. _this.USESPHERICALINVERTEX = false;
  40252. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40253. _this.LODINREFLECTIONALPHA = false;
  40254. _this.GAMMAREFLECTION = false;
  40255. _this.RADIANCEOCCLUSION = false;
  40256. _this.HORIZONOCCLUSION = false;
  40257. _this.REFRACTION = false;
  40258. _this.REFRACTIONMAP_3D = false;
  40259. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40260. _this.LODINREFRACTIONALPHA = false;
  40261. _this.GAMMAREFRACTION = false;
  40262. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40263. _this.INSTANCES = false;
  40264. _this.NUM_BONE_INFLUENCERS = 0;
  40265. _this.BonesPerMesh = 0;
  40266. _this.NONUNIFORMSCALING = false;
  40267. _this.MORPHTARGETS = false;
  40268. _this.MORPHTARGETS_NORMAL = false;
  40269. _this.MORPHTARGETS_TANGENT = false;
  40270. _this.NUM_MORPH_INFLUENCERS = 0;
  40271. _this.IMAGEPROCESSING = false;
  40272. _this.VIGNETTE = false;
  40273. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40274. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40275. _this.TONEMAPPING = false;
  40276. _this.CONTRAST = false;
  40277. _this.COLORCURVES = false;
  40278. _this.COLORGRADING = false;
  40279. _this.COLORGRADING3D = false;
  40280. _this.SAMPLER3DGREENDEPTH = false;
  40281. _this.SAMPLER3DBGRMAP = false;
  40282. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40283. _this.EXPOSURE = false;
  40284. _this.USEPHYSICALLIGHTFALLOFF = false;
  40285. _this.TWOSIDEDLIGHTING = false;
  40286. _this.SHADOWFLOAT = false;
  40287. _this.CLIPPLANE = false;
  40288. _this.POINTSIZE = false;
  40289. _this.FOG = false;
  40290. _this.LOGARITHMICDEPTH = false;
  40291. _this.FORCENORMALFORWARD = false;
  40292. _this.rebuild();
  40293. return _this;
  40294. }
  40295. /**
  40296. * Resets the PBR Material defines.
  40297. */
  40298. PBRMaterialDefines.prototype.reset = function () {
  40299. _super.prototype.reset.call(this);
  40300. this.ALPHATESTVALUE = 0.5;
  40301. this.PBR = true;
  40302. };
  40303. return PBRMaterialDefines;
  40304. }(BABYLON.MaterialDefines));
  40305. /**
  40306. * The Physically based material base class of BJS.
  40307. *
  40308. * This offers the main features of a standard PBR material.
  40309. * For more information, please refer to the documentation :
  40310. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40311. */
  40312. var PBRBaseMaterial = /** @class */ (function (_super) {
  40313. __extends(PBRBaseMaterial, _super);
  40314. /**
  40315. * Instantiates a new PBRMaterial instance.
  40316. *
  40317. * @param name The material name
  40318. * @param scene The scene the material will be use in.
  40319. */
  40320. function PBRBaseMaterial(name, scene) {
  40321. var _this = _super.call(this, name, scene) || this;
  40322. /**
  40323. * Intensity of the direct lights e.g. the four lights available in your scene.
  40324. * This impacts both the direct diffuse and specular highlights.
  40325. */
  40326. _this._directIntensity = 1.0;
  40327. /**
  40328. * Intensity of the emissive part of the material.
  40329. * This helps controlling the emissive effect without modifying the emissive color.
  40330. */
  40331. _this._emissiveIntensity = 1.0;
  40332. /**
  40333. * Intensity of the environment e.g. how much the environment will light the object
  40334. * either through harmonics for rough material or through the refelction for shiny ones.
  40335. */
  40336. _this._environmentIntensity = 1.0;
  40337. /**
  40338. * This is a special control allowing the reduction of the specular highlights coming from the
  40339. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40340. */
  40341. _this._specularIntensity = 1.0;
  40342. /**
  40343. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40344. */
  40345. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40346. /**
  40347. * Debug Control allowing disabling the bump map on this material.
  40348. */
  40349. _this._disableBumpMap = false;
  40350. /**
  40351. * AKA Occlusion Texture Intensity in other nomenclature.
  40352. */
  40353. _this._ambientTextureStrength = 1.0;
  40354. /**
  40355. * The color of a material in ambient lighting.
  40356. */
  40357. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40358. /**
  40359. * AKA Diffuse Color in other nomenclature.
  40360. */
  40361. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40362. /**
  40363. * AKA Specular Color in other nomenclature.
  40364. */
  40365. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40366. /**
  40367. * The color applied when light is reflected from a material.
  40368. */
  40369. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40370. /**
  40371. * The color applied when light is emitted from a material.
  40372. */
  40373. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40374. /**
  40375. * AKA Glossiness in other nomenclature.
  40376. */
  40377. _this._microSurface = 0.9;
  40378. /**
  40379. * source material index of refraction (IOR)' / 'destination material IOR.
  40380. */
  40381. _this._indexOfRefraction = 0.66;
  40382. /**
  40383. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40384. */
  40385. _this._invertRefractionY = false;
  40386. /**
  40387. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40388. * Materials half opaque for instance using refraction could benefit from this control.
  40389. */
  40390. _this._linkRefractionWithTransparency = false;
  40391. /**
  40392. * Specifies that the material will use the light map as a show map.
  40393. */
  40394. _this._useLightmapAsShadowmap = false;
  40395. /**
  40396. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40397. * makes the reflect vector face the model (under horizon).
  40398. */
  40399. _this._useHorizonOcclusion = true;
  40400. /**
  40401. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40402. * too much the area relying on ambient texture to define their ambient occlusion.
  40403. */
  40404. _this._useRadianceOcclusion = true;
  40405. /**
  40406. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40407. */
  40408. _this._useAlphaFromAlbedoTexture = false;
  40409. /**
  40410. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40411. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40412. */
  40413. _this._useSpecularOverAlpha = true;
  40414. /**
  40415. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40416. */
  40417. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40418. /**
  40419. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40420. */
  40421. _this._useRoughnessFromMetallicTextureAlpha = true;
  40422. /**
  40423. * Specifies if the metallic texture contains the roughness information in its green channel.
  40424. */
  40425. _this._useRoughnessFromMetallicTextureGreen = false;
  40426. /**
  40427. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40428. */
  40429. _this._useMetallnessFromMetallicTextureBlue = false;
  40430. /**
  40431. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40432. */
  40433. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40434. /**
  40435. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40436. */
  40437. _this._useAmbientInGrayScale = false;
  40438. /**
  40439. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40440. * The material will try to infer what glossiness each pixel should be.
  40441. */
  40442. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40443. /**
  40444. * BJS is using an harcoded light falloff based on a manually sets up range.
  40445. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40446. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40447. */
  40448. _this._usePhysicalLightFalloff = true;
  40449. /**
  40450. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40451. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40452. */
  40453. _this._useRadianceOverAlpha = true;
  40454. /**
  40455. * Allows using an object space normal map (instead of tangent space).
  40456. */
  40457. _this._useObjectSpaceNormalMap = false;
  40458. /**
  40459. * Allows using the bump map in parallax mode.
  40460. */
  40461. _this._useParallax = false;
  40462. /**
  40463. * Allows using the bump map in parallax occlusion mode.
  40464. */
  40465. _this._useParallaxOcclusion = false;
  40466. /**
  40467. * Controls the scale bias of the parallax mode.
  40468. */
  40469. _this._parallaxScaleBias = 0.05;
  40470. /**
  40471. * If sets to true, disables all the lights affecting the material.
  40472. */
  40473. _this._disableLighting = false;
  40474. /**
  40475. * Number of Simultaneous lights allowed on the material.
  40476. */
  40477. _this._maxSimultaneousLights = 4;
  40478. /**
  40479. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40480. */
  40481. _this._invertNormalMapX = false;
  40482. /**
  40483. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40484. */
  40485. _this._invertNormalMapY = false;
  40486. /**
  40487. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40488. */
  40489. _this._twoSidedLighting = false;
  40490. /**
  40491. * Defines the alpha limits in alpha test mode.
  40492. */
  40493. _this._alphaCutOff = 0.4;
  40494. /**
  40495. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40496. */
  40497. _this._forceAlphaTest = false;
  40498. /**
  40499. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40500. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40501. */
  40502. _this._useAlphaFresnel = false;
  40503. /**
  40504. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40505. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40506. */
  40507. _this._useLinearAlphaFresnel = false;
  40508. /**
  40509. * The transparency mode of the material.
  40510. */
  40511. _this._transparencyMode = null;
  40512. /**
  40513. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40514. * from cos thetav and roughness:
  40515. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40516. */
  40517. _this._environmentBRDFTexture = null;
  40518. /**
  40519. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40520. */
  40521. _this._forceIrradianceInFragment = false;
  40522. /**
  40523. * Force normal to face away from face.
  40524. */
  40525. _this._forceNormalForward = false;
  40526. /**
  40527. * Force metallic workflow.
  40528. */
  40529. _this._forceMetallicWorkflow = false;
  40530. /**
  40531. * Stores the available render targets.
  40532. */
  40533. _this._renderTargets = new BABYLON.SmartArray(16);
  40534. /**
  40535. * Sets the global ambient color for the material used in lighting calculations.
  40536. */
  40537. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40538. // Setup the default processing configuration to the scene.
  40539. _this._attachImageProcessingConfiguration(null);
  40540. _this.getRenderTargetTextures = function () {
  40541. _this._renderTargets.reset();
  40542. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40543. _this._renderTargets.push(_this._reflectionTexture);
  40544. }
  40545. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40546. _this._renderTargets.push(_this._refractionTexture);
  40547. }
  40548. return _this._renderTargets;
  40549. };
  40550. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40551. return _this;
  40552. }
  40553. /**
  40554. * Attaches a new image processing configuration to the PBR Material.
  40555. * @param configuration
  40556. */
  40557. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40558. var _this = this;
  40559. if (configuration === this._imageProcessingConfiguration) {
  40560. return;
  40561. }
  40562. // Detaches observer.
  40563. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40564. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40565. }
  40566. // Pick the scene configuration if needed.
  40567. if (!configuration) {
  40568. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40569. }
  40570. else {
  40571. this._imageProcessingConfiguration = configuration;
  40572. }
  40573. // Attaches observer.
  40574. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40575. _this._markAllSubMeshesAsImageProcessingDirty();
  40576. });
  40577. };
  40578. /**
  40579. * Gets the name of the material class.
  40580. */
  40581. PBRBaseMaterial.prototype.getClassName = function () {
  40582. return "PBRBaseMaterial";
  40583. };
  40584. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40585. /**
  40586. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40587. */
  40588. get: function () {
  40589. return this._useLogarithmicDepth;
  40590. },
  40591. /**
  40592. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40593. */
  40594. set: function (value) {
  40595. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40601. /**
  40602. * Gets the current transparency mode.
  40603. */
  40604. get: function () {
  40605. return this._transparencyMode;
  40606. },
  40607. /**
  40608. * Sets the transparency mode of the material.
  40609. */
  40610. set: function (value) {
  40611. if (this._transparencyMode === value) {
  40612. return;
  40613. }
  40614. this._transparencyMode = value;
  40615. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40616. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40622. /**
  40623. * Returns true if alpha blending should be disabled.
  40624. */
  40625. get: function () {
  40626. return (this._linkRefractionWithTransparency ||
  40627. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40628. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. /**
  40634. * Specifies whether or not this material should be rendered in alpha blend mode.
  40635. */
  40636. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40637. if (this._disableAlphaBlending) {
  40638. return false;
  40639. }
  40640. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40641. };
  40642. /**
  40643. * Specifies if the mesh will require alpha blending.
  40644. * @param mesh - BJS mesh.
  40645. */
  40646. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40647. if (this._disableAlphaBlending) {
  40648. return false;
  40649. }
  40650. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40651. };
  40652. /**
  40653. * Specifies whether or not this material should be rendered in alpha test mode.
  40654. */
  40655. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40656. if (this._forceAlphaTest) {
  40657. return true;
  40658. }
  40659. if (this._linkRefractionWithTransparency) {
  40660. return false;
  40661. }
  40662. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40663. };
  40664. /**
  40665. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40666. */
  40667. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40668. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40669. };
  40670. /**
  40671. * Gets the texture used for the alpha test.
  40672. */
  40673. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40674. return this._albedoTexture;
  40675. };
  40676. /**
  40677. * Specifies that the submesh is ready to be used.
  40678. * @param mesh - BJS mesh.
  40679. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40680. * @param useInstances - Specifies that instances should be used.
  40681. * @returns - boolean indicating that the submesh is ready or not.
  40682. */
  40683. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40684. if (subMesh.effect && this.isFrozen) {
  40685. if (this._wasPreviouslyReady) {
  40686. return true;
  40687. }
  40688. }
  40689. if (!subMesh._materialDefines) {
  40690. subMesh._materialDefines = new PBRMaterialDefines();
  40691. }
  40692. var defines = subMesh._materialDefines;
  40693. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40694. if (defines._renderId === this.getScene().getRenderId()) {
  40695. return true;
  40696. }
  40697. }
  40698. var scene = this.getScene();
  40699. var engine = scene.getEngine();
  40700. if (defines._areTexturesDirty) {
  40701. if (scene.texturesEnabled) {
  40702. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40703. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40704. return false;
  40705. }
  40706. }
  40707. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40708. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40709. return false;
  40710. }
  40711. }
  40712. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40713. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40714. return false;
  40715. }
  40716. }
  40717. var reflectionTexture = this._getReflectionTexture();
  40718. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40719. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40720. return false;
  40721. }
  40722. }
  40723. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40724. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40725. return false;
  40726. }
  40727. }
  40728. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40729. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40730. return false;
  40731. }
  40732. }
  40733. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40734. if (this._metallicTexture) {
  40735. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40736. return false;
  40737. }
  40738. }
  40739. else if (this._reflectivityTexture) {
  40740. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40741. return false;
  40742. }
  40743. }
  40744. if (this._microSurfaceTexture) {
  40745. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40746. return false;
  40747. }
  40748. }
  40749. }
  40750. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40751. // Bump texture cannot be not blocking.
  40752. if (!this._bumpTexture.isReady()) {
  40753. return false;
  40754. }
  40755. }
  40756. var refractionTexture = this._getRefractionTexture();
  40757. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40758. if (!refractionTexture.isReadyOrNotBlocking()) {
  40759. return false;
  40760. }
  40761. }
  40762. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40763. // This is blocking.
  40764. if (!this._environmentBRDFTexture.isReady()) {
  40765. return false;
  40766. }
  40767. }
  40768. }
  40769. }
  40770. if (defines._areImageProcessingDirty) {
  40771. if (!this._imageProcessingConfiguration.isReady()) {
  40772. return false;
  40773. }
  40774. }
  40775. if (!engine.getCaps().standardDerivatives) {
  40776. var bufferMesh = null;
  40777. if (mesh.getClassName() === "InstancedMesh") {
  40778. bufferMesh = mesh.sourceMesh;
  40779. }
  40780. else if (mesh.getClassName() === "Mesh") {
  40781. bufferMesh = mesh;
  40782. }
  40783. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40784. bufferMesh.createNormals(true);
  40785. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40786. }
  40787. }
  40788. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40789. if (effect) {
  40790. scene.resetCachedMaterial();
  40791. subMesh.setEffect(effect, defines);
  40792. this.buildUniformLayout();
  40793. }
  40794. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40795. return false;
  40796. }
  40797. defines._renderId = scene.getRenderId();
  40798. this._wasPreviouslyReady = true;
  40799. return true;
  40800. };
  40801. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40802. if (onCompiled === void 0) { onCompiled = null; }
  40803. if (onError === void 0) { onError = null; }
  40804. if (useInstances === void 0) { useInstances = null; }
  40805. if (useClipPlane === void 0) { useClipPlane = null; }
  40806. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40807. if (!defines.isDirty) {
  40808. return null;
  40809. }
  40810. defines.markAsProcessed();
  40811. var scene = this.getScene();
  40812. var engine = scene.getEngine();
  40813. // Fallbacks
  40814. var fallbacks = new BABYLON.EffectFallbacks();
  40815. var fallbackRank = 0;
  40816. if (defines.USESPHERICALINVERTEX) {
  40817. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40818. }
  40819. if (defines.FOG) {
  40820. fallbacks.addFallback(fallbackRank, "FOG");
  40821. }
  40822. if (defines.POINTSIZE) {
  40823. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40824. }
  40825. if (defines.LOGARITHMICDEPTH) {
  40826. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40827. }
  40828. if (defines.PARALLAX) {
  40829. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40830. }
  40831. if (defines.PARALLAXOCCLUSION) {
  40832. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40833. }
  40834. if (defines.ENVIRONMENTBRDF) {
  40835. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40836. }
  40837. if (defines.TANGENT) {
  40838. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40839. }
  40840. if (defines.BUMP) {
  40841. fallbacks.addFallback(fallbackRank++, "BUMP");
  40842. }
  40843. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40844. if (defines.SPECULARTERM) {
  40845. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40846. }
  40847. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40848. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40849. }
  40850. if (defines.LIGHTMAP) {
  40851. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40852. }
  40853. if (defines.NORMAL) {
  40854. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40855. }
  40856. if (defines.AMBIENT) {
  40857. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40858. }
  40859. if (defines.EMISSIVE) {
  40860. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40861. }
  40862. if (defines.VERTEXCOLOR) {
  40863. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40864. }
  40865. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40866. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40867. }
  40868. if (defines.MORPHTARGETS) {
  40869. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40870. }
  40871. //Attributes
  40872. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40873. if (defines.NORMAL) {
  40874. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40875. }
  40876. if (defines.TANGENT) {
  40877. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40878. }
  40879. if (defines.UV1) {
  40880. attribs.push(BABYLON.VertexBuffer.UVKind);
  40881. }
  40882. if (defines.UV2) {
  40883. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40884. }
  40885. if (defines.VERTEXCOLOR) {
  40886. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40887. }
  40888. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40889. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40890. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40891. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40892. "vFogInfos", "vFogColor", "pointSize",
  40893. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40894. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40895. "mBones",
  40896. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40897. "vLightingIntensity",
  40898. "logarithmicDepthConstant",
  40899. "vSphericalX", "vSphericalY", "vSphericalZ",
  40900. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40901. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40902. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40903. "vTangentSpaceParams"
  40904. ];
  40905. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40906. "bumpSampler", "lightmapSampler", "opacitySampler",
  40907. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40908. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40909. "microSurfaceSampler", "environmentBrdfSampler"];
  40910. var uniformBuffers = ["Material", "Scene"];
  40911. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40912. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40913. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40914. uniformsNames: uniforms,
  40915. uniformBuffersNames: uniformBuffers,
  40916. samplers: samplers,
  40917. defines: defines,
  40918. maxSimultaneousLights: this._maxSimultaneousLights
  40919. });
  40920. var join = defines.toString();
  40921. return engine.createEffect("pbr", {
  40922. attributes: attribs,
  40923. uniformsNames: uniforms,
  40924. uniformBuffersNames: uniformBuffers,
  40925. samplers: samplers,
  40926. defines: join,
  40927. fallbacks: fallbacks,
  40928. onCompiled: onCompiled,
  40929. onError: onError,
  40930. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40931. }, engine);
  40932. };
  40933. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40934. if (useInstances === void 0) { useInstances = null; }
  40935. if (useClipPlane === void 0) { useClipPlane = null; }
  40936. var scene = this.getScene();
  40937. var engine = scene.getEngine();
  40938. // Lights
  40939. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40940. defines._needNormals = true;
  40941. // Textures
  40942. if (defines._areTexturesDirty) {
  40943. defines._needUVs = false;
  40944. if (scene.texturesEnabled) {
  40945. if (scene.getEngine().getCaps().textureLOD) {
  40946. defines.LODBASEDMICROSFURACE = true;
  40947. }
  40948. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40950. }
  40951. else {
  40952. defines.ALBEDO = false;
  40953. }
  40954. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40955. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40956. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40957. }
  40958. else {
  40959. defines.AMBIENT = false;
  40960. }
  40961. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40962. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40963. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40964. }
  40965. else {
  40966. defines.OPACITY = false;
  40967. }
  40968. var reflectionTexture = this._getReflectionTexture();
  40969. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40970. defines.REFLECTION = true;
  40971. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40972. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40973. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40974. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40975. defines.INVERTCUBICMAP = true;
  40976. }
  40977. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40978. switch (reflectionTexture.coordinatesMode) {
  40979. case BABYLON.Texture.CUBIC_MODE:
  40980. case BABYLON.Texture.INVCUBIC_MODE:
  40981. defines.REFLECTIONMAP_CUBIC = true;
  40982. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40983. break;
  40984. case BABYLON.Texture.EXPLICIT_MODE:
  40985. defines.REFLECTIONMAP_EXPLICIT = true;
  40986. break;
  40987. case BABYLON.Texture.PLANAR_MODE:
  40988. defines.REFLECTIONMAP_PLANAR = true;
  40989. break;
  40990. case BABYLON.Texture.PROJECTION_MODE:
  40991. defines.REFLECTIONMAP_PROJECTION = true;
  40992. break;
  40993. case BABYLON.Texture.SKYBOX_MODE:
  40994. defines.REFLECTIONMAP_SKYBOX = true;
  40995. break;
  40996. case BABYLON.Texture.SPHERICAL_MODE:
  40997. defines.REFLECTIONMAP_SPHERICAL = true;
  40998. break;
  40999. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41000. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41001. break;
  41002. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41003. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41004. break;
  41005. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41006. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41007. break;
  41008. }
  41009. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41010. if (reflectionTexture.sphericalPolynomial) {
  41011. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41012. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41013. defines.USESPHERICALINVERTEX = false;
  41014. }
  41015. else {
  41016. defines.USESPHERICALINVERTEX = true;
  41017. }
  41018. }
  41019. }
  41020. }
  41021. else {
  41022. defines.REFLECTION = false;
  41023. defines.REFLECTIONMAP_3D = false;
  41024. defines.REFLECTIONMAP_SPHERICAL = false;
  41025. defines.REFLECTIONMAP_PLANAR = false;
  41026. defines.REFLECTIONMAP_CUBIC = false;
  41027. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41028. defines.REFLECTIONMAP_PROJECTION = false;
  41029. defines.REFLECTIONMAP_SKYBOX = false;
  41030. defines.REFLECTIONMAP_EXPLICIT = false;
  41031. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41032. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41033. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41034. defines.INVERTCUBICMAP = false;
  41035. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41036. defines.USESPHERICALINVERTEX = false;
  41037. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41038. defines.LODINREFLECTIONALPHA = false;
  41039. defines.GAMMAREFLECTION = false;
  41040. }
  41041. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41043. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41044. }
  41045. else {
  41046. defines.LIGHTMAP = false;
  41047. }
  41048. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41050. }
  41051. else {
  41052. defines.EMISSIVE = false;
  41053. }
  41054. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41055. if (this._metallicTexture) {
  41056. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41057. defines.METALLICWORKFLOW = true;
  41058. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41059. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41060. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41061. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41062. }
  41063. else if (this._reflectivityTexture) {
  41064. defines.METALLICWORKFLOW = false;
  41065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41066. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41067. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41068. }
  41069. else {
  41070. defines.METALLICWORKFLOW = false;
  41071. defines.REFLECTIVITY = false;
  41072. }
  41073. if (this._microSurfaceTexture) {
  41074. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41075. }
  41076. else {
  41077. defines.MICROSURFACEMAP = false;
  41078. }
  41079. }
  41080. else {
  41081. defines.REFLECTIVITY = false;
  41082. defines.MICROSURFACEMAP = false;
  41083. }
  41084. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41086. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41087. defines.PARALLAX = true;
  41088. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41089. }
  41090. else {
  41091. defines.PARALLAX = false;
  41092. }
  41093. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41094. }
  41095. else {
  41096. defines.BUMP = false;
  41097. }
  41098. var refractionTexture = this._getRefractionTexture();
  41099. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41100. defines.REFRACTION = true;
  41101. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41102. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41103. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41104. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41105. if (this._linkRefractionWithTransparency) {
  41106. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41107. }
  41108. }
  41109. else {
  41110. defines.REFRACTION = false;
  41111. }
  41112. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41113. defines.ENVIRONMENTBRDF = true;
  41114. }
  41115. else {
  41116. defines.ENVIRONMENTBRDF = false;
  41117. }
  41118. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41119. defines.ALPHAFROMALBEDO = true;
  41120. }
  41121. else {
  41122. defines.ALPHAFROMALBEDO = false;
  41123. }
  41124. }
  41125. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41126. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41127. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41128. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41129. defines.METALLICWORKFLOW = true;
  41130. }
  41131. else {
  41132. defines.METALLICWORKFLOW = false;
  41133. }
  41134. if (!this.backFaceCulling && this._twoSidedLighting) {
  41135. defines.TWOSIDEDLIGHTING = true;
  41136. }
  41137. else {
  41138. defines.TWOSIDEDLIGHTING = false;
  41139. }
  41140. defines.ALPHATESTVALUE = this._alphaCutOff;
  41141. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41142. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41143. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41144. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41145. }
  41146. if (defines._areImageProcessingDirty) {
  41147. this._imageProcessingConfiguration.prepareDefines(defines);
  41148. }
  41149. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41150. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41151. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41152. // Misc.
  41153. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41154. // Values that need to be evaluated on every frame
  41155. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41156. // Attribs
  41157. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41158. };
  41159. /**
  41160. * Force shader compilation
  41161. */
  41162. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41163. var _this = this;
  41164. var localOptions = __assign({ clipPlane: false }, options);
  41165. var defines = new PBRMaterialDefines();
  41166. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41167. if (effect.isReady()) {
  41168. if (onCompiled) {
  41169. onCompiled(this);
  41170. }
  41171. }
  41172. else {
  41173. effect.onCompileObservable.add(function () {
  41174. if (onCompiled) {
  41175. onCompiled(_this);
  41176. }
  41177. });
  41178. }
  41179. };
  41180. /**
  41181. * Initializes the uniform buffer layout for the shader.
  41182. */
  41183. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41184. // Order is important !
  41185. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41186. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41187. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41188. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41189. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41190. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41191. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41192. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41193. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41194. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41195. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41196. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41197. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41198. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41199. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41200. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41201. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41202. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41203. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41204. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41205. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41206. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41207. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41208. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41209. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41210. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41211. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41212. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41213. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41214. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41215. this._uniformBuffer.addUniform("pointSize", 1);
  41216. this._uniformBuffer.create();
  41217. };
  41218. /**
  41219. * Unbinds the textures.
  41220. */
  41221. PBRBaseMaterial.prototype.unbind = function () {
  41222. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41223. this._uniformBuffer.setTexture("reflectionSampler", null);
  41224. }
  41225. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41226. this._uniformBuffer.setTexture("refractionSampler", null);
  41227. }
  41228. _super.prototype.unbind.call(this);
  41229. };
  41230. /**
  41231. * Binds the submesh data.
  41232. * @param world - The world matrix.
  41233. * @param mesh - The BJS mesh.
  41234. * @param subMesh - A submesh of the BJS mesh.
  41235. */
  41236. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41237. var scene = this.getScene();
  41238. var defines = subMesh._materialDefines;
  41239. if (!defines) {
  41240. return;
  41241. }
  41242. var effect = subMesh.effect;
  41243. if (!effect) {
  41244. return;
  41245. }
  41246. this._activeEffect = effect;
  41247. // Matrices
  41248. this.bindOnlyWorldMatrix(world);
  41249. // Normal Matrix
  41250. if (defines.OBJECTSPACE_NORMALMAP) {
  41251. world.toNormalMatrix(this._normalMatrix);
  41252. this.bindOnlyNormalMatrix(this._normalMatrix);
  41253. }
  41254. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41255. // Bones
  41256. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41257. var reflectionTexture = null;
  41258. if (mustRebind) {
  41259. this._uniformBuffer.bindToEffect(effect, "Material");
  41260. this.bindViewProjection(effect);
  41261. reflectionTexture = this._getReflectionTexture();
  41262. var refractionTexture = this._getRefractionTexture();
  41263. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41264. // Texture uniforms
  41265. if (scene.texturesEnabled) {
  41266. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41267. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41268. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41269. }
  41270. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41271. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41272. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41273. }
  41274. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41275. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41276. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41277. }
  41278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41279. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41280. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41281. if (reflectionTexture.boundingBoxSize) {
  41282. var cubeTexture = reflectionTexture;
  41283. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41284. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41285. }
  41286. var polynomials = reflectionTexture.sphericalPolynomial;
  41287. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41288. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41289. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41290. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41291. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41292. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41293. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41294. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41295. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41296. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41297. }
  41298. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41299. }
  41300. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41301. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41302. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41303. }
  41304. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41305. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41306. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41307. }
  41308. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41309. if (this._metallicTexture) {
  41310. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41311. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41312. }
  41313. else if (this._reflectivityTexture) {
  41314. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41315. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41316. }
  41317. if (this._microSurfaceTexture) {
  41318. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41319. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41320. }
  41321. }
  41322. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41323. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41324. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41325. if (scene._mirroredCameraPosition) {
  41326. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41327. }
  41328. else {
  41329. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41330. }
  41331. }
  41332. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41333. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41334. var depth = 1.0;
  41335. if (!refractionTexture.isCube) {
  41336. if (refractionTexture.depth) {
  41337. depth = refractionTexture.depth;
  41338. }
  41339. }
  41340. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41341. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41342. }
  41343. }
  41344. // Point size
  41345. if (this.pointsCloud) {
  41346. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41347. }
  41348. // Colors
  41349. if (defines.METALLICWORKFLOW) {
  41350. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41351. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41352. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41353. }
  41354. else {
  41355. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41356. }
  41357. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41358. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41359. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41360. // Misc
  41361. this._lightingInfos.x = this._directIntensity;
  41362. this._lightingInfos.y = this._emissiveIntensity;
  41363. this._lightingInfos.z = this._environmentIntensity;
  41364. this._lightingInfos.w = this._specularIntensity;
  41365. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41366. }
  41367. // Textures
  41368. if (scene.texturesEnabled) {
  41369. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41370. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41371. }
  41372. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41373. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41374. }
  41375. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41376. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41377. }
  41378. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41379. if (defines.LODBASEDMICROSFURACE) {
  41380. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41381. }
  41382. else {
  41383. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41384. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41385. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41386. }
  41387. }
  41388. if (defines.ENVIRONMENTBRDF) {
  41389. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41390. }
  41391. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41392. if (defines.LODBASEDMICROSFURACE) {
  41393. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41394. }
  41395. else {
  41396. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41397. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41398. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41399. }
  41400. }
  41401. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41402. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41403. }
  41404. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41405. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41406. }
  41407. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41408. if (this._metallicTexture) {
  41409. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41410. }
  41411. else if (this._reflectivityTexture) {
  41412. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41413. }
  41414. if (this._microSurfaceTexture) {
  41415. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41416. }
  41417. }
  41418. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41419. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41420. }
  41421. }
  41422. // Clip plane
  41423. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41424. // Colors
  41425. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41426. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41427. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41428. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41429. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41430. }
  41431. if (mustRebind || !this.isFrozen) {
  41432. // Lights
  41433. if (scene.lightsEnabled && !this._disableLighting) {
  41434. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41435. }
  41436. // View
  41437. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41438. this.bindView(effect);
  41439. }
  41440. // Fog
  41441. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41442. // Morph targets
  41443. if (defines.NUM_MORPH_INFLUENCERS) {
  41444. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41445. }
  41446. // image processing
  41447. this._imageProcessingConfiguration.bind(this._activeEffect);
  41448. // Log. depth
  41449. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41450. }
  41451. this._uniformBuffer.update();
  41452. this._afterBind(mesh);
  41453. };
  41454. /**
  41455. * Returns the animatable textures.
  41456. * @returns - Array of animatable textures.
  41457. */
  41458. PBRBaseMaterial.prototype.getAnimatables = function () {
  41459. var results = [];
  41460. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41461. results.push(this._albedoTexture);
  41462. }
  41463. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41464. results.push(this._ambientTexture);
  41465. }
  41466. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41467. results.push(this._opacityTexture);
  41468. }
  41469. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41470. results.push(this._reflectionTexture);
  41471. }
  41472. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41473. results.push(this._emissiveTexture);
  41474. }
  41475. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41476. results.push(this._metallicTexture);
  41477. }
  41478. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41479. results.push(this._reflectivityTexture);
  41480. }
  41481. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41482. results.push(this._bumpTexture);
  41483. }
  41484. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41485. results.push(this._lightmapTexture);
  41486. }
  41487. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41488. results.push(this._refractionTexture);
  41489. }
  41490. return results;
  41491. };
  41492. /**
  41493. * Returns the texture used for reflections.
  41494. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41495. */
  41496. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41497. if (this._reflectionTexture) {
  41498. return this._reflectionTexture;
  41499. }
  41500. return this.getScene().environmentTexture;
  41501. };
  41502. /**
  41503. * Returns the texture used for refraction or null if none is used.
  41504. * @returns - Refection texture if present. If no refraction texture and refraction
  41505. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41506. */
  41507. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41508. if (this._refractionTexture) {
  41509. return this._refractionTexture;
  41510. }
  41511. if (this._linkRefractionWithTransparency) {
  41512. return this.getScene().environmentTexture;
  41513. }
  41514. return null;
  41515. };
  41516. /**
  41517. * Disposes the resources of the material.
  41518. * @param forceDisposeEffect - Forces the disposal of effects.
  41519. * @param forceDisposeTextures - Forces the disposal of all textures.
  41520. */
  41521. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41522. if (forceDisposeTextures) {
  41523. if (this._albedoTexture) {
  41524. this._albedoTexture.dispose();
  41525. }
  41526. if (this._ambientTexture) {
  41527. this._ambientTexture.dispose();
  41528. }
  41529. if (this._opacityTexture) {
  41530. this._opacityTexture.dispose();
  41531. }
  41532. if (this._reflectionTexture) {
  41533. this._reflectionTexture.dispose();
  41534. }
  41535. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41536. this._environmentBRDFTexture.dispose();
  41537. }
  41538. if (this._emissiveTexture) {
  41539. this._emissiveTexture.dispose();
  41540. }
  41541. if (this._metallicTexture) {
  41542. this._metallicTexture.dispose();
  41543. }
  41544. if (this._reflectivityTexture) {
  41545. this._reflectivityTexture.dispose();
  41546. }
  41547. if (this._bumpTexture) {
  41548. this._bumpTexture.dispose();
  41549. }
  41550. if (this._lightmapTexture) {
  41551. this._lightmapTexture.dispose();
  41552. }
  41553. if (this._refractionTexture) {
  41554. this._refractionTexture.dispose();
  41555. }
  41556. }
  41557. this._renderTargets.dispose();
  41558. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41559. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41560. }
  41561. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41562. };
  41563. /**
  41564. * Stores the reflectivity values based on metallic roughness workflow.
  41565. */
  41566. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41567. __decorate([
  41568. BABYLON.serializeAsImageProcessingConfiguration()
  41569. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41570. __decorate([
  41571. BABYLON.serialize()
  41572. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41573. __decorate([
  41574. BABYLON.serialize()
  41575. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41576. return PBRBaseMaterial;
  41577. }(BABYLON.PushMaterial));
  41578. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41579. })(BABYLON || (BABYLON = {}));
  41580. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41581. var BABYLON;
  41582. (function (BABYLON) {
  41583. /**
  41584. * The Physically based simple base material of BJS.
  41585. *
  41586. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41587. * It is used as the base class for both the specGloss and metalRough conventions.
  41588. */
  41589. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41590. __extends(PBRBaseSimpleMaterial, _super);
  41591. /**
  41592. * Instantiates a new PBRMaterial instance.
  41593. *
  41594. * @param name The material name
  41595. * @param scene The scene the material will be use in.
  41596. */
  41597. function PBRBaseSimpleMaterial(name, scene) {
  41598. var _this = _super.call(this, name, scene) || this;
  41599. /**
  41600. * Number of Simultaneous lights allowed on the material.
  41601. */
  41602. _this.maxSimultaneousLights = 4;
  41603. /**
  41604. * If sets to true, disables all the lights affecting the material.
  41605. */
  41606. _this.disableLighting = false;
  41607. /**
  41608. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41609. */
  41610. _this.invertNormalMapX = false;
  41611. /**
  41612. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41613. */
  41614. _this.invertNormalMapY = false;
  41615. /**
  41616. * Emissivie color used to self-illuminate the model.
  41617. */
  41618. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41619. /**
  41620. * Occlusion Channel Strenght.
  41621. */
  41622. _this.occlusionStrength = 1.0;
  41623. _this.useLightmapAsShadowmap = false;
  41624. _this._useAlphaFromAlbedoTexture = true;
  41625. _this._useAmbientInGrayScale = true;
  41626. return _this;
  41627. }
  41628. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41629. /**
  41630. * Gets the current double sided mode.
  41631. */
  41632. get: function () {
  41633. return this._twoSidedLighting;
  41634. },
  41635. /**
  41636. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41637. */
  41638. set: function (value) {
  41639. if (this._twoSidedLighting === value) {
  41640. return;
  41641. }
  41642. this._twoSidedLighting = value;
  41643. this.backFaceCulling = !value;
  41644. this._markAllSubMeshesAsTexturesDirty();
  41645. },
  41646. enumerable: true,
  41647. configurable: true
  41648. });
  41649. /**
  41650. * Return the active textures of the material.
  41651. */
  41652. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41653. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41654. if (this.environmentTexture) {
  41655. activeTextures.push(this.environmentTexture);
  41656. }
  41657. if (this.normalTexture) {
  41658. activeTextures.push(this.normalTexture);
  41659. }
  41660. if (this.emissiveTexture) {
  41661. activeTextures.push(this.emissiveTexture);
  41662. }
  41663. if (this.occlusionTexture) {
  41664. activeTextures.push(this.occlusionTexture);
  41665. }
  41666. if (this.lightmapTexture) {
  41667. activeTextures.push(this.lightmapTexture);
  41668. }
  41669. return activeTextures;
  41670. };
  41671. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41672. if (_super.prototype.hasTexture.call(this, texture)) {
  41673. return true;
  41674. }
  41675. if (this.lightmapTexture === texture) {
  41676. return true;
  41677. }
  41678. return false;
  41679. };
  41680. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41681. return "PBRBaseSimpleMaterial";
  41682. };
  41683. __decorate([
  41684. BABYLON.serialize(),
  41685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41686. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41687. __decorate([
  41688. BABYLON.serialize(),
  41689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41690. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41691. __decorate([
  41692. BABYLON.serializeAsTexture(),
  41693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41694. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41695. __decorate([
  41696. BABYLON.serialize(),
  41697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41698. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41699. __decorate([
  41700. BABYLON.serialize(),
  41701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41702. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41703. __decorate([
  41704. BABYLON.serializeAsTexture(),
  41705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41706. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41707. __decorate([
  41708. BABYLON.serializeAsColor3("emissive"),
  41709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41710. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41711. __decorate([
  41712. BABYLON.serializeAsTexture(),
  41713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41714. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41715. __decorate([
  41716. BABYLON.serialize(),
  41717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41718. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41719. __decorate([
  41720. BABYLON.serializeAsTexture(),
  41721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41722. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41723. __decorate([
  41724. BABYLON.serialize(),
  41725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41726. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41727. __decorate([
  41728. BABYLON.serialize()
  41729. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41730. __decorate([
  41731. BABYLON.serializeAsTexture(),
  41732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41733. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41734. __decorate([
  41735. BABYLON.serialize(),
  41736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41737. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41738. return PBRBaseSimpleMaterial;
  41739. }(BABYLON.PBRBaseMaterial));
  41740. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41741. })(BABYLON || (BABYLON = {}));
  41742. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41743. var BABYLON;
  41744. (function (BABYLON) {
  41745. /**
  41746. * The Physically based material of BJS.
  41747. *
  41748. * This offers the main features of a standard PBR material.
  41749. * For more information, please refer to the documentation :
  41750. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41751. */
  41752. var PBRMaterial = /** @class */ (function (_super) {
  41753. __extends(PBRMaterial, _super);
  41754. /**
  41755. * Instantiates a new PBRMaterial instance.
  41756. *
  41757. * @param name The material name
  41758. * @param scene The scene the material will be use in.
  41759. */
  41760. function PBRMaterial(name, scene) {
  41761. var _this = _super.call(this, name, scene) || this;
  41762. /**
  41763. * Intensity of the direct lights e.g. the four lights available in your scene.
  41764. * This impacts both the direct diffuse and specular highlights.
  41765. */
  41766. _this.directIntensity = 1.0;
  41767. /**
  41768. * Intensity of the emissive part of the material.
  41769. * This helps controlling the emissive effect without modifying the emissive color.
  41770. */
  41771. _this.emissiveIntensity = 1.0;
  41772. /**
  41773. * Intensity of the environment e.g. how much the environment will light the object
  41774. * either through harmonics for rough material or through the refelction for shiny ones.
  41775. */
  41776. _this.environmentIntensity = 1.0;
  41777. /**
  41778. * This is a special control allowing the reduction of the specular highlights coming from the
  41779. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41780. */
  41781. _this.specularIntensity = 1.0;
  41782. /**
  41783. * Debug Control allowing disabling the bump map on this material.
  41784. */
  41785. _this.disableBumpMap = false;
  41786. /**
  41787. * AKA Occlusion Texture Intensity in other nomenclature.
  41788. */
  41789. _this.ambientTextureStrength = 1.0;
  41790. /**
  41791. * The color of a material in ambient lighting.
  41792. */
  41793. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41794. /**
  41795. * AKA Diffuse Color in other nomenclature.
  41796. */
  41797. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41798. /**
  41799. * AKA Specular Color in other nomenclature.
  41800. */
  41801. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41802. /**
  41803. * The color reflected from the material.
  41804. */
  41805. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41806. /**
  41807. * The color emitted from the material.
  41808. */
  41809. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41810. /**
  41811. * AKA Glossiness in other nomenclature.
  41812. */
  41813. _this.microSurface = 1.0;
  41814. /**
  41815. * source material index of refraction (IOR)' / 'destination material IOR.
  41816. */
  41817. _this.indexOfRefraction = 0.66;
  41818. /**
  41819. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41820. */
  41821. _this.invertRefractionY = false;
  41822. /**
  41823. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41824. * Materials half opaque for instance using refraction could benefit from this control.
  41825. */
  41826. _this.linkRefractionWithTransparency = false;
  41827. _this.useLightmapAsShadowmap = false;
  41828. /**
  41829. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41830. */
  41831. _this.useAlphaFromAlbedoTexture = false;
  41832. /**
  41833. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41834. */
  41835. _this.forceAlphaTest = false;
  41836. /**
  41837. * Defines the alpha limits in alpha test mode.
  41838. */
  41839. _this.alphaCutOff = 0.4;
  41840. /**
  41841. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41842. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41843. */
  41844. _this.useSpecularOverAlpha = true;
  41845. /**
  41846. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41847. */
  41848. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41849. /**
  41850. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41851. */
  41852. _this.useRoughnessFromMetallicTextureAlpha = true;
  41853. /**
  41854. * Specifies if the metallic texture contains the roughness information in its green channel.
  41855. */
  41856. _this.useRoughnessFromMetallicTextureGreen = false;
  41857. /**
  41858. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41859. */
  41860. _this.useMetallnessFromMetallicTextureBlue = false;
  41861. /**
  41862. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41863. */
  41864. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41865. /**
  41866. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41867. */
  41868. _this.useAmbientInGrayScale = false;
  41869. /**
  41870. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41871. * The material will try to infer what glossiness each pixel should be.
  41872. */
  41873. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41874. /**
  41875. * BJS is using an harcoded light falloff based on a manually sets up range.
  41876. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41877. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41878. */
  41879. _this.usePhysicalLightFalloff = true;
  41880. /**
  41881. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41882. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41883. */
  41884. _this.useRadianceOverAlpha = true;
  41885. /**
  41886. * Allows using an object space normal map (instead of tangent space).
  41887. */
  41888. _this.useObjectSpaceNormalMap = false;
  41889. /**
  41890. * Allows using the bump map in parallax mode.
  41891. */
  41892. _this.useParallax = false;
  41893. /**
  41894. * Allows using the bump map in parallax occlusion mode.
  41895. */
  41896. _this.useParallaxOcclusion = false;
  41897. /**
  41898. * Controls the scale bias of the parallax mode.
  41899. */
  41900. _this.parallaxScaleBias = 0.05;
  41901. /**
  41902. * If sets to true, disables all the lights affecting the material.
  41903. */
  41904. _this.disableLighting = false;
  41905. /**
  41906. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41907. */
  41908. _this.forceIrradianceInFragment = false;
  41909. /**
  41910. * Number of Simultaneous lights allowed on the material.
  41911. */
  41912. _this.maxSimultaneousLights = 4;
  41913. /**
  41914. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41915. */
  41916. _this.invertNormalMapX = false;
  41917. /**
  41918. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41919. */
  41920. _this.invertNormalMapY = false;
  41921. /**
  41922. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41923. */
  41924. _this.twoSidedLighting = false;
  41925. /**
  41926. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41927. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41928. */
  41929. _this.useAlphaFresnel = false;
  41930. /**
  41931. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41932. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41933. */
  41934. _this.useLinearAlphaFresnel = false;
  41935. /**
  41936. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41937. * And/Or occlude the blended part.
  41938. */
  41939. _this.environmentBRDFTexture = null;
  41940. /**
  41941. * Force normal to face away from face.
  41942. */
  41943. _this.forceNormalForward = false;
  41944. /**
  41945. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41946. * makes the reflect vector face the model (under horizon).
  41947. */
  41948. _this.useHorizonOcclusion = true;
  41949. /**
  41950. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41951. * too much the area relying on ambient texture to define their ambient occlusion.
  41952. */
  41953. _this.useRadianceOcclusion = true;
  41954. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41955. return _this;
  41956. }
  41957. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41958. /**
  41959. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41960. */
  41961. get: function () {
  41962. return this._PBRMATERIAL_OPAQUE;
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41968. /**
  41969. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41970. */
  41971. get: function () {
  41972. return this._PBRMATERIAL_ALPHATEST;
  41973. },
  41974. enumerable: true,
  41975. configurable: true
  41976. });
  41977. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41978. /**
  41979. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41980. */
  41981. get: function () {
  41982. return this._PBRMATERIAL_ALPHABLEND;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41988. /**
  41989. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41990. * They are also discarded below the alpha cutoff threshold to improve performances.
  41991. */
  41992. get: function () {
  41993. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41994. },
  41995. enumerable: true,
  41996. configurable: true
  41997. });
  41998. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41999. /**
  42000. * Gets the image processing configuration used either in this material.
  42001. */
  42002. get: function () {
  42003. return this._imageProcessingConfiguration;
  42004. },
  42005. /**
  42006. * Sets the Default image processing configuration used either in the this material.
  42007. *
  42008. * If sets to null, the scene one is in use.
  42009. */
  42010. set: function (value) {
  42011. this._attachImageProcessingConfiguration(value);
  42012. // Ensure the effect will be rebuilt.
  42013. this._markAllSubMeshesAsTexturesDirty();
  42014. },
  42015. enumerable: true,
  42016. configurable: true
  42017. });
  42018. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42019. /**
  42020. * Gets wether the color curves effect is enabled.
  42021. */
  42022. get: function () {
  42023. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42024. },
  42025. /**
  42026. * Sets wether the color curves effect is enabled.
  42027. */
  42028. set: function (value) {
  42029. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42035. /**
  42036. * Gets wether the color grading effect is enabled.
  42037. */
  42038. get: function () {
  42039. return this.imageProcessingConfiguration.colorGradingEnabled;
  42040. },
  42041. /**
  42042. * Gets wether the color grading effect is enabled.
  42043. */
  42044. set: function (value) {
  42045. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42046. },
  42047. enumerable: true,
  42048. configurable: true
  42049. });
  42050. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42051. /**
  42052. * Gets wether tonemapping is enabled or not.
  42053. */
  42054. get: function () {
  42055. return this._imageProcessingConfiguration.toneMappingEnabled;
  42056. },
  42057. /**
  42058. * Sets wether tonemapping is enabled or not
  42059. */
  42060. set: function (value) {
  42061. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. ;
  42067. ;
  42068. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42069. /**
  42070. * The camera exposure used on this material.
  42071. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42072. * This corresponds to a photographic exposure.
  42073. */
  42074. get: function () {
  42075. return this._imageProcessingConfiguration.exposure;
  42076. },
  42077. /**
  42078. * The camera exposure used on this material.
  42079. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42080. * This corresponds to a photographic exposure.
  42081. */
  42082. set: function (value) {
  42083. this._imageProcessingConfiguration.exposure = value;
  42084. },
  42085. enumerable: true,
  42086. configurable: true
  42087. });
  42088. ;
  42089. ;
  42090. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42091. /**
  42092. * Gets The camera contrast used on this material.
  42093. */
  42094. get: function () {
  42095. return this._imageProcessingConfiguration.contrast;
  42096. },
  42097. /**
  42098. * Sets The camera contrast used on this material.
  42099. */
  42100. set: function (value) {
  42101. this._imageProcessingConfiguration.contrast = value;
  42102. },
  42103. enumerable: true,
  42104. configurable: true
  42105. });
  42106. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42107. /**
  42108. * Gets the Color Grading 2D Lookup Texture.
  42109. */
  42110. get: function () {
  42111. return this._imageProcessingConfiguration.colorGradingTexture;
  42112. },
  42113. /**
  42114. * Sets the Color Grading 2D Lookup Texture.
  42115. */
  42116. set: function (value) {
  42117. this._imageProcessingConfiguration.colorGradingTexture = value;
  42118. },
  42119. enumerable: true,
  42120. configurable: true
  42121. });
  42122. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42123. /**
  42124. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42125. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42126. * 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;
  42127. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42128. */
  42129. get: function () {
  42130. return this._imageProcessingConfiguration.colorCurves;
  42131. },
  42132. /**
  42133. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42134. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42135. * 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;
  42136. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42137. */
  42138. set: function (value) {
  42139. this._imageProcessingConfiguration.colorCurves = value;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. /**
  42145. * Returns the name of this material class.
  42146. */
  42147. PBRMaterial.prototype.getClassName = function () {
  42148. return "PBRMaterial";
  42149. };
  42150. /**
  42151. * Returns an array of the actively used textures.
  42152. * @returns - Array of BaseTextures
  42153. */
  42154. PBRMaterial.prototype.getActiveTextures = function () {
  42155. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42156. if (this._albedoTexture) {
  42157. activeTextures.push(this._albedoTexture);
  42158. }
  42159. if (this._ambientTexture) {
  42160. activeTextures.push(this._ambientTexture);
  42161. }
  42162. if (this._opacityTexture) {
  42163. activeTextures.push(this._opacityTexture);
  42164. }
  42165. if (this._reflectionTexture) {
  42166. activeTextures.push(this._reflectionTexture);
  42167. }
  42168. if (this._emissiveTexture) {
  42169. activeTextures.push(this._emissiveTexture);
  42170. }
  42171. if (this._reflectivityTexture) {
  42172. activeTextures.push(this._reflectivityTexture);
  42173. }
  42174. if (this._metallicTexture) {
  42175. activeTextures.push(this._metallicTexture);
  42176. }
  42177. if (this._microSurfaceTexture) {
  42178. activeTextures.push(this._microSurfaceTexture);
  42179. }
  42180. if (this._bumpTexture) {
  42181. activeTextures.push(this._bumpTexture);
  42182. }
  42183. if (this._lightmapTexture) {
  42184. activeTextures.push(this._lightmapTexture);
  42185. }
  42186. if (this._refractionTexture) {
  42187. activeTextures.push(this._refractionTexture);
  42188. }
  42189. return activeTextures;
  42190. };
  42191. /**
  42192. * Checks to see if a texture is used in the material.
  42193. * @param texture - Base texture to use.
  42194. * @returns - Boolean specifying if a texture is used in the material.
  42195. */
  42196. PBRMaterial.prototype.hasTexture = function (texture) {
  42197. if (_super.prototype.hasTexture.call(this, texture)) {
  42198. return true;
  42199. }
  42200. if (this._albedoTexture === texture) {
  42201. return true;
  42202. }
  42203. if (this._ambientTexture === texture) {
  42204. return true;
  42205. }
  42206. if (this._opacityTexture === texture) {
  42207. return true;
  42208. }
  42209. if (this._reflectionTexture === texture) {
  42210. return true;
  42211. }
  42212. if (this._reflectivityTexture === texture) {
  42213. return true;
  42214. }
  42215. if (this._metallicTexture === texture) {
  42216. return true;
  42217. }
  42218. if (this._microSurfaceTexture === texture) {
  42219. return true;
  42220. }
  42221. if (this._bumpTexture === texture) {
  42222. return true;
  42223. }
  42224. if (this._lightmapTexture === texture) {
  42225. return true;
  42226. }
  42227. if (this._refractionTexture === texture) {
  42228. return true;
  42229. }
  42230. return false;
  42231. };
  42232. /**
  42233. * Makes a duplicate of the current material.
  42234. * @param name - name to use for the new material.
  42235. */
  42236. PBRMaterial.prototype.clone = function (name) {
  42237. var _this = this;
  42238. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42239. clone.id = name;
  42240. clone.name = name;
  42241. return clone;
  42242. };
  42243. /**
  42244. * Serializes this PBR Material.
  42245. * @returns - An object with the serialized material.
  42246. */
  42247. PBRMaterial.prototype.serialize = function () {
  42248. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42249. serializationObject.customType = "BABYLON.PBRMaterial";
  42250. return serializationObject;
  42251. };
  42252. // Statics
  42253. /**
  42254. * Parses a PBR Material from a serialized object.
  42255. * @param source - Serialized object.
  42256. * @param scene - BJS scene instance.
  42257. * @param rootUrl - url for the scene object
  42258. * @returns - PBRMaterial
  42259. */
  42260. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42261. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42262. };
  42263. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42264. /**
  42265. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42266. */
  42267. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42268. /**
  42269. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42270. */
  42271. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42272. /**
  42273. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42274. * They are also discarded below the alpha cutoff threshold to improve performances.
  42275. */
  42276. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42277. __decorate([
  42278. BABYLON.serialize(),
  42279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42280. ], PBRMaterial.prototype, "directIntensity", void 0);
  42281. __decorate([
  42282. BABYLON.serialize(),
  42283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42284. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42285. __decorate([
  42286. BABYLON.serialize(),
  42287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42288. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42289. __decorate([
  42290. BABYLON.serialize(),
  42291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42292. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42293. __decorate([
  42294. BABYLON.serialize(),
  42295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42296. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42297. __decorate([
  42298. BABYLON.serializeAsTexture(),
  42299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42300. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42301. __decorate([
  42302. BABYLON.serializeAsTexture(),
  42303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42304. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42305. __decorate([
  42306. BABYLON.serialize(),
  42307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42308. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42309. __decorate([
  42310. BABYLON.serializeAsTexture(),
  42311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42312. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42313. __decorate([
  42314. BABYLON.serializeAsTexture(),
  42315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42316. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42317. __decorate([
  42318. BABYLON.serializeAsTexture(),
  42319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42320. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42321. __decorate([
  42322. BABYLON.serializeAsTexture(),
  42323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42324. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42325. __decorate([
  42326. BABYLON.serializeAsTexture(),
  42327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42328. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42329. __decorate([
  42330. BABYLON.serialize(),
  42331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42332. ], PBRMaterial.prototype, "metallic", void 0);
  42333. __decorate([
  42334. BABYLON.serialize(),
  42335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42336. ], PBRMaterial.prototype, "roughness", void 0);
  42337. __decorate([
  42338. BABYLON.serializeAsTexture(),
  42339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42340. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42341. __decorate([
  42342. BABYLON.serializeAsTexture(),
  42343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42344. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42345. __decorate([
  42346. BABYLON.serializeAsTexture(),
  42347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42348. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42349. __decorate([
  42350. BABYLON.serializeAsTexture(),
  42351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42352. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42353. __decorate([
  42354. BABYLON.serializeAsColor3("ambient"),
  42355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42356. ], PBRMaterial.prototype, "ambientColor", void 0);
  42357. __decorate([
  42358. BABYLON.serializeAsColor3("albedo"),
  42359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42360. ], PBRMaterial.prototype, "albedoColor", void 0);
  42361. __decorate([
  42362. BABYLON.serializeAsColor3("reflectivity"),
  42363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42364. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42365. __decorate([
  42366. BABYLON.serializeAsColor3("reflection"),
  42367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42368. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42369. __decorate([
  42370. BABYLON.serializeAsColor3("emissive"),
  42371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42372. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42373. __decorate([
  42374. BABYLON.serialize(),
  42375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42376. ], PBRMaterial.prototype, "microSurface", void 0);
  42377. __decorate([
  42378. BABYLON.serialize(),
  42379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42380. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42381. __decorate([
  42382. BABYLON.serialize(),
  42383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42384. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42385. __decorate([
  42386. BABYLON.serialize(),
  42387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42388. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42389. __decorate([
  42390. BABYLON.serialize(),
  42391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42392. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42393. __decorate([
  42394. BABYLON.serialize(),
  42395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42396. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42397. __decorate([
  42398. BABYLON.serialize(),
  42399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42400. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42401. __decorate([
  42402. BABYLON.serialize(),
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42404. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42405. __decorate([
  42406. BABYLON.serialize(),
  42407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42408. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42409. __decorate([
  42410. BABYLON.serialize(),
  42411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42412. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42413. __decorate([
  42414. BABYLON.serialize(),
  42415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42416. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42417. __decorate([
  42418. BABYLON.serialize(),
  42419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42420. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42421. __decorate([
  42422. BABYLON.serialize(),
  42423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42424. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42425. __decorate([
  42426. BABYLON.serialize(),
  42427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42428. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42429. __decorate([
  42430. BABYLON.serialize(),
  42431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42432. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42433. __decorate([
  42434. BABYLON.serialize(),
  42435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42436. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42437. __decorate([
  42438. BABYLON.serialize(),
  42439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42440. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42441. __decorate([
  42442. BABYLON.serialize(),
  42443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42444. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42445. __decorate([
  42446. BABYLON.serialize(),
  42447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42448. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42449. __decorate([
  42450. BABYLON.serialize(),
  42451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42452. ], PBRMaterial.prototype, "useParallax", void 0);
  42453. __decorate([
  42454. BABYLON.serialize(),
  42455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42456. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42457. __decorate([
  42458. BABYLON.serialize(),
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42460. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42461. __decorate([
  42462. BABYLON.serialize(),
  42463. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42464. ], PBRMaterial.prototype, "disableLighting", void 0);
  42465. __decorate([
  42466. BABYLON.serialize(),
  42467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42468. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42469. __decorate([
  42470. BABYLON.serialize(),
  42471. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42472. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42473. __decorate([
  42474. BABYLON.serialize(),
  42475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42476. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42477. __decorate([
  42478. BABYLON.serialize(),
  42479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42480. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42481. __decorate([
  42482. BABYLON.serialize(),
  42483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42484. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42485. __decorate([
  42486. BABYLON.serialize(),
  42487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42488. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42489. __decorate([
  42490. BABYLON.serialize(),
  42491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42492. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42493. __decorate([
  42494. BABYLON.serializeAsTexture(),
  42495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42496. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42497. __decorate([
  42498. BABYLON.serialize(),
  42499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42500. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42501. __decorate([
  42502. BABYLON.serialize(),
  42503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42504. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42505. __decorate([
  42506. BABYLON.serialize(),
  42507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42508. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42509. return PBRMaterial;
  42510. }(BABYLON.PBRBaseMaterial));
  42511. BABYLON.PBRMaterial = PBRMaterial;
  42512. })(BABYLON || (BABYLON = {}));
  42513. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42514. var BABYLON;
  42515. (function (BABYLON) {
  42516. /**
  42517. * The PBR material of BJS following the metal roughness convention.
  42518. *
  42519. * This fits to the PBR convention in the GLTF definition:
  42520. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42521. */
  42522. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42523. __extends(PBRMetallicRoughnessMaterial, _super);
  42524. /**
  42525. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42526. *
  42527. * @param name The material name
  42528. * @param scene The scene the material will be use in.
  42529. */
  42530. function PBRMetallicRoughnessMaterial(name, scene) {
  42531. var _this = _super.call(this, name, scene) || this;
  42532. _this._useRoughnessFromMetallicTextureAlpha = false;
  42533. _this._useRoughnessFromMetallicTextureGreen = true;
  42534. _this._useMetallnessFromMetallicTextureBlue = true;
  42535. _this._forceMetallicWorkflow = true;
  42536. return _this;
  42537. }
  42538. /**
  42539. * Return the currrent class name of the material.
  42540. */
  42541. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42542. return "PBRMetallicRoughnessMaterial";
  42543. };
  42544. /**
  42545. * Return the active textures of the material.
  42546. */
  42547. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42548. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42549. if (this.baseTexture) {
  42550. activeTextures.push(this.baseTexture);
  42551. }
  42552. if (this.metallicRoughnessTexture) {
  42553. activeTextures.push(this.metallicRoughnessTexture);
  42554. }
  42555. return activeTextures;
  42556. };
  42557. /**
  42558. * Checks to see if a texture is used in the material.
  42559. * @param texture - Base texture to use.
  42560. * @returns - Boolean specifying if a texture is used in the material.
  42561. */
  42562. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42563. if (_super.prototype.hasTexture.call(this, texture)) {
  42564. return true;
  42565. }
  42566. if (this.baseTexture === texture) {
  42567. return true;
  42568. }
  42569. if (this.metallicRoughnessTexture === texture) {
  42570. return true;
  42571. }
  42572. return false;
  42573. };
  42574. /**
  42575. * Makes a duplicate of the current material.
  42576. * @param name - name to use for the new material.
  42577. */
  42578. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42579. var _this = this;
  42580. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42581. clone.id = name;
  42582. clone.name = name;
  42583. return clone;
  42584. };
  42585. /**
  42586. * Serialize the material to a parsable JSON object.
  42587. */
  42588. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42589. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42590. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42591. return serializationObject;
  42592. };
  42593. /**
  42594. * Parses a JSON object correponding to the serialize function.
  42595. */
  42596. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42597. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42598. };
  42599. __decorate([
  42600. BABYLON.serializeAsColor3(),
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42602. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42603. __decorate([
  42604. BABYLON.serializeAsTexture(),
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42606. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42607. __decorate([
  42608. BABYLON.serialize(),
  42609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42610. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42611. __decorate([
  42612. BABYLON.serialize(),
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42615. __decorate([
  42616. BABYLON.serializeAsTexture(),
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42618. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42619. return PBRMetallicRoughnessMaterial;
  42620. }(BABYLON.PBRBaseSimpleMaterial));
  42621. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42622. })(BABYLON || (BABYLON = {}));
  42623. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42624. var BABYLON;
  42625. (function (BABYLON) {
  42626. /**
  42627. * The PBR material of BJS following the specular glossiness convention.
  42628. *
  42629. * This fits to the PBR convention in the GLTF definition:
  42630. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42631. */
  42632. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42633. __extends(PBRSpecularGlossinessMaterial, _super);
  42634. /**
  42635. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42636. *
  42637. * @param name The material name
  42638. * @param scene The scene the material will be use in.
  42639. */
  42640. function PBRSpecularGlossinessMaterial(name, scene) {
  42641. var _this = _super.call(this, name, scene) || this;
  42642. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42643. return _this;
  42644. }
  42645. /**
  42646. * Return the currrent class name of the material.
  42647. */
  42648. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42649. return "PBRSpecularGlossinessMaterial";
  42650. };
  42651. /**
  42652. * Return the active textures of the material.
  42653. */
  42654. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42655. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42656. if (this.diffuseTexture) {
  42657. activeTextures.push(this.diffuseTexture);
  42658. }
  42659. if (this.specularGlossinessTexture) {
  42660. activeTextures.push(this.specularGlossinessTexture);
  42661. }
  42662. return activeTextures;
  42663. };
  42664. /**
  42665. * Checks to see if a texture is used in the material.
  42666. * @param texture - Base texture to use.
  42667. * @returns - Boolean specifying if a texture is used in the material.
  42668. */
  42669. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42670. if (_super.prototype.hasTexture.call(this, texture)) {
  42671. return true;
  42672. }
  42673. if (this.diffuseTexture === texture) {
  42674. return true;
  42675. }
  42676. if (this.specularGlossinessTexture === texture) {
  42677. return true;
  42678. }
  42679. return false;
  42680. };
  42681. /**
  42682. * Makes a duplicate of the current material.
  42683. * @param name - name to use for the new material.
  42684. */
  42685. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42686. var _this = this;
  42687. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42688. clone.id = name;
  42689. clone.name = name;
  42690. return clone;
  42691. };
  42692. /**
  42693. * Serialize the material to a parsable JSON object.
  42694. */
  42695. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42697. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42698. return serializationObject;
  42699. };
  42700. /**
  42701. * Parses a JSON object correponding to the serialize function.
  42702. */
  42703. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42704. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42705. };
  42706. __decorate([
  42707. BABYLON.serializeAsColor3("diffuse"),
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42709. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsTexture(),
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42713. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42714. __decorate([
  42715. BABYLON.serializeAsColor3("specular"),
  42716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42717. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42718. __decorate([
  42719. BABYLON.serialize(),
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42721. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsTexture(),
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42725. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42726. return PBRSpecularGlossinessMaterial;
  42727. }(BABYLON.PBRBaseSimpleMaterial));
  42728. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42729. })(BABYLON || (BABYLON = {}));
  42730. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42731. var BABYLON;
  42732. (function (BABYLON) {
  42733. BABYLON.CameraInputTypes = {};
  42734. var CameraInputsManager = /** @class */ (function () {
  42735. function CameraInputsManager(camera) {
  42736. this.attached = {};
  42737. this.camera = camera;
  42738. this.checkInputs = function () { };
  42739. }
  42740. /**
  42741. * Add an input method to a camera.
  42742. * builtin inputs example: camera.inputs.addGamepad();
  42743. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42744. * @param input camera input method
  42745. */
  42746. CameraInputsManager.prototype.add = function (input) {
  42747. var type = input.getSimpleName();
  42748. if (this.attached[type]) {
  42749. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42750. return;
  42751. }
  42752. this.attached[type] = input;
  42753. input.camera = this.camera;
  42754. //for checkInputs, we are dynamically creating a function
  42755. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42756. if (input.checkInputs) {
  42757. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42758. }
  42759. if (this.attachedElement) {
  42760. input.attachControl(this.attachedElement);
  42761. }
  42762. };
  42763. /**
  42764. * Remove a specific input method from a camera
  42765. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42766. * @param inputToRemove camera input method
  42767. */
  42768. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42769. for (var cam in this.attached) {
  42770. var input = this.attached[cam];
  42771. if (input === inputToRemove) {
  42772. input.detachControl(this.attachedElement);
  42773. input.camera = null;
  42774. delete this.attached[cam];
  42775. this.rebuildInputCheck();
  42776. }
  42777. }
  42778. };
  42779. CameraInputsManager.prototype.removeByType = function (inputType) {
  42780. for (var cam in this.attached) {
  42781. var input = this.attached[cam];
  42782. if (input.getClassName() === inputType) {
  42783. input.detachControl(this.attachedElement);
  42784. input.camera = null;
  42785. delete this.attached[cam];
  42786. this.rebuildInputCheck();
  42787. }
  42788. }
  42789. };
  42790. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42791. var current = this.checkInputs;
  42792. return function () {
  42793. current();
  42794. fn();
  42795. };
  42796. };
  42797. CameraInputsManager.prototype.attachInput = function (input) {
  42798. if (this.attachedElement) {
  42799. input.attachControl(this.attachedElement, this.noPreventDefault);
  42800. }
  42801. };
  42802. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42803. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42804. if (this.attachedElement) {
  42805. return;
  42806. }
  42807. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42808. this.attachedElement = element;
  42809. this.noPreventDefault = noPreventDefault;
  42810. for (var cam in this.attached) {
  42811. this.attached[cam].attachControl(element, noPreventDefault);
  42812. }
  42813. };
  42814. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42815. if (disconnect === void 0) { disconnect = false; }
  42816. if (this.attachedElement !== element) {
  42817. return;
  42818. }
  42819. for (var cam in this.attached) {
  42820. this.attached[cam].detachControl(element);
  42821. if (disconnect) {
  42822. this.attached[cam].camera = null;
  42823. }
  42824. }
  42825. this.attachedElement = null;
  42826. };
  42827. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42828. this.checkInputs = function () { };
  42829. for (var cam in this.attached) {
  42830. var input = this.attached[cam];
  42831. if (input.checkInputs) {
  42832. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42833. }
  42834. }
  42835. };
  42836. /**
  42837. * Remove all attached input methods from a camera
  42838. */
  42839. CameraInputsManager.prototype.clear = function () {
  42840. if (this.attachedElement) {
  42841. this.detachElement(this.attachedElement, true);
  42842. }
  42843. this.attached = {};
  42844. this.attachedElement = null;
  42845. this.checkInputs = function () { };
  42846. };
  42847. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42848. var inputs = {};
  42849. for (var cam in this.attached) {
  42850. var input = this.attached[cam];
  42851. var res = BABYLON.SerializationHelper.Serialize(input);
  42852. inputs[input.getClassName()] = res;
  42853. }
  42854. serializedCamera.inputsmgr = inputs;
  42855. };
  42856. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42857. var parsedInputs = parsedCamera.inputsmgr;
  42858. if (parsedInputs) {
  42859. this.clear();
  42860. for (var n in parsedInputs) {
  42861. var construct = BABYLON.CameraInputTypes[n];
  42862. if (construct) {
  42863. var parsedinput = parsedInputs[n];
  42864. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42865. this.add(input);
  42866. }
  42867. }
  42868. }
  42869. else {
  42870. //2016-03-08 this part is for managing backward compatibility
  42871. for (var n in this.attached) {
  42872. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42873. if (construct) {
  42874. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42875. this.remove(this.attached[n]);
  42876. this.add(input);
  42877. }
  42878. }
  42879. }
  42880. };
  42881. return CameraInputsManager;
  42882. }());
  42883. BABYLON.CameraInputsManager = CameraInputsManager;
  42884. })(BABYLON || (BABYLON = {}));
  42885. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42886. var BABYLON;
  42887. (function (BABYLON) {
  42888. var TargetCamera = /** @class */ (function (_super) {
  42889. __extends(TargetCamera, _super);
  42890. function TargetCamera(name, position, scene) {
  42891. var _this = _super.call(this, name, position, scene) || this;
  42892. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42893. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42894. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42895. _this.speed = 2.0;
  42896. _this.noRotationConstraint = false;
  42897. _this.lockedTarget = null;
  42898. _this._currentTarget = BABYLON.Vector3.Zero();
  42899. _this._viewMatrix = BABYLON.Matrix.Zero();
  42900. _this._camMatrix = BABYLON.Matrix.Zero();
  42901. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42902. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42903. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42904. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42905. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42906. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42907. _this._tempMatrix = BABYLON.Matrix.Zero();
  42908. return _this;
  42909. }
  42910. TargetCamera.prototype.getFrontPosition = function (distance) {
  42911. this.getWorldMatrix();
  42912. var direction = this.getTarget().subtract(this.position);
  42913. direction.normalize();
  42914. direction.scaleInPlace(distance);
  42915. return this.globalPosition.add(direction);
  42916. };
  42917. TargetCamera.prototype._getLockedTargetPosition = function () {
  42918. if (!this.lockedTarget) {
  42919. return null;
  42920. }
  42921. if (this.lockedTarget.absolutePosition) {
  42922. this.lockedTarget.computeWorldMatrix();
  42923. }
  42924. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42925. };
  42926. TargetCamera.prototype.storeState = function () {
  42927. this._storedPosition = this.position.clone();
  42928. this._storedRotation = this.rotation.clone();
  42929. if (this.rotationQuaternion) {
  42930. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42931. }
  42932. return _super.prototype.storeState.call(this);
  42933. };
  42934. /**
  42935. * Restored camera state. You must call storeState() first
  42936. */
  42937. TargetCamera.prototype._restoreStateValues = function () {
  42938. if (!_super.prototype._restoreStateValues.call(this)) {
  42939. return false;
  42940. }
  42941. this.position = this._storedPosition.clone();
  42942. this.rotation = this._storedRotation.clone();
  42943. if (this.rotationQuaternion) {
  42944. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42945. }
  42946. this.cameraDirection.copyFromFloats(0, 0, 0);
  42947. this.cameraRotation.copyFromFloats(0, 0);
  42948. return true;
  42949. };
  42950. // Cache
  42951. TargetCamera.prototype._initCache = function () {
  42952. _super.prototype._initCache.call(this);
  42953. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42954. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42955. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42956. };
  42957. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42958. if (!ignoreParentClass) {
  42959. _super.prototype._updateCache.call(this);
  42960. }
  42961. var lockedTargetPosition = this._getLockedTargetPosition();
  42962. if (!lockedTargetPosition) {
  42963. this._cache.lockedTarget = null;
  42964. }
  42965. else {
  42966. if (!this._cache.lockedTarget) {
  42967. this._cache.lockedTarget = lockedTargetPosition.clone();
  42968. }
  42969. else {
  42970. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42971. }
  42972. }
  42973. this._cache.rotation.copyFrom(this.rotation);
  42974. if (this.rotationQuaternion)
  42975. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42976. };
  42977. // Synchronized
  42978. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42979. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42980. return false;
  42981. }
  42982. var lockedTargetPosition = this._getLockedTargetPosition();
  42983. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42984. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42985. };
  42986. // Methods
  42987. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42988. var engine = this.getEngine();
  42989. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42990. };
  42991. // Target
  42992. TargetCamera.prototype.setTarget = function (target) {
  42993. this.upVector.normalize();
  42994. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42995. this._camMatrix.invert();
  42996. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42997. var vDir = target.subtract(this.position);
  42998. if (vDir.x >= 0.0) {
  42999. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43000. }
  43001. else {
  43002. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43003. }
  43004. this.rotation.z = 0;
  43005. if (isNaN(this.rotation.x)) {
  43006. this.rotation.x = 0;
  43007. }
  43008. if (isNaN(this.rotation.y)) {
  43009. this.rotation.y = 0;
  43010. }
  43011. if (isNaN(this.rotation.z)) {
  43012. this.rotation.z = 0;
  43013. }
  43014. if (this.rotationQuaternion) {
  43015. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43016. }
  43017. };
  43018. /**
  43019. * Return the current target position of the camera. This value is expressed in local space.
  43020. */
  43021. TargetCamera.prototype.getTarget = function () {
  43022. return this._currentTarget;
  43023. };
  43024. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43025. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43026. };
  43027. TargetCamera.prototype._updatePosition = function () {
  43028. if (this.parent) {
  43029. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43030. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43031. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43032. return;
  43033. }
  43034. this.position.addInPlace(this.cameraDirection);
  43035. };
  43036. TargetCamera.prototype._checkInputs = function () {
  43037. var needToMove = this._decideIfNeedsToMove();
  43038. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43039. // Move
  43040. if (needToMove) {
  43041. this._updatePosition();
  43042. }
  43043. // Rotate
  43044. if (needToRotate) {
  43045. this.rotation.x += this.cameraRotation.x;
  43046. this.rotation.y += this.cameraRotation.y;
  43047. //rotate, if quaternion is set and rotation was used
  43048. if (this.rotationQuaternion) {
  43049. var len = this.rotation.lengthSquared();
  43050. if (len) {
  43051. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43052. }
  43053. }
  43054. if (!this.noRotationConstraint) {
  43055. var limit = (Math.PI / 2) * 0.95;
  43056. if (this.rotation.x > limit)
  43057. this.rotation.x = limit;
  43058. if (this.rotation.x < -limit)
  43059. this.rotation.x = -limit;
  43060. }
  43061. }
  43062. // Inertia
  43063. if (needToMove) {
  43064. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43065. this.cameraDirection.x = 0;
  43066. }
  43067. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43068. this.cameraDirection.y = 0;
  43069. }
  43070. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43071. this.cameraDirection.z = 0;
  43072. }
  43073. this.cameraDirection.scaleInPlace(this.inertia);
  43074. }
  43075. if (needToRotate) {
  43076. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43077. this.cameraRotation.x = 0;
  43078. }
  43079. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43080. this.cameraRotation.y = 0;
  43081. }
  43082. this.cameraRotation.scaleInPlace(this.inertia);
  43083. }
  43084. _super.prototype._checkInputs.call(this);
  43085. };
  43086. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43087. if (this.rotationQuaternion) {
  43088. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43089. }
  43090. else {
  43091. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43092. }
  43093. //update the up vector!
  43094. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43095. };
  43096. TargetCamera.prototype._getViewMatrix = function () {
  43097. if (this.lockedTarget) {
  43098. this.setTarget(this._getLockedTargetPosition());
  43099. }
  43100. // Compute
  43101. this._updateCameraRotationMatrix();
  43102. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43103. // Computing target and final matrix
  43104. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43105. if (this.getScene().useRightHandedSystem) {
  43106. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43107. }
  43108. else {
  43109. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43110. }
  43111. return this._viewMatrix;
  43112. };
  43113. /**
  43114. * @override
  43115. * Override Camera.createRigCamera
  43116. */
  43117. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43118. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43119. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43120. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43121. if (!this.rotationQuaternion) {
  43122. this.rotationQuaternion = new BABYLON.Quaternion();
  43123. }
  43124. rigCamera._cameraRigParams = {};
  43125. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43126. }
  43127. return rigCamera;
  43128. }
  43129. return null;
  43130. };
  43131. /**
  43132. * @override
  43133. * Override Camera._updateRigCameras
  43134. */
  43135. TargetCamera.prototype._updateRigCameras = function () {
  43136. var camLeft = this._rigCameras[0];
  43137. var camRight = this._rigCameras[1];
  43138. switch (this.cameraRigMode) {
  43139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43140. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43141. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43142. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43143. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43144. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43145. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43146. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43147. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43148. camLeft.setTarget(this.getTarget());
  43149. camRight.setTarget(this.getTarget());
  43150. break;
  43151. case BABYLON.Camera.RIG_MODE_VR:
  43152. if (camLeft.rotationQuaternion) {
  43153. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43154. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43155. }
  43156. else {
  43157. camLeft.rotation.copyFrom(this.rotation);
  43158. camRight.rotation.copyFrom(this.rotation);
  43159. }
  43160. camLeft.position.copyFrom(this.position);
  43161. camRight.position.copyFrom(this.position);
  43162. break;
  43163. }
  43164. _super.prototype._updateRigCameras.call(this);
  43165. };
  43166. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43167. if (!this._rigCamTransformMatrix) {
  43168. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43169. }
  43170. var target = this.getTarget();
  43171. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43172. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43173. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43174. };
  43175. TargetCamera.prototype.getClassName = function () {
  43176. return "TargetCamera";
  43177. };
  43178. __decorate([
  43179. BABYLON.serializeAsVector3()
  43180. ], TargetCamera.prototype, "rotation", void 0);
  43181. __decorate([
  43182. BABYLON.serialize()
  43183. ], TargetCamera.prototype, "speed", void 0);
  43184. __decorate([
  43185. BABYLON.serializeAsMeshReference("lockedTargetId")
  43186. ], TargetCamera.prototype, "lockedTarget", void 0);
  43187. return TargetCamera;
  43188. }(BABYLON.Camera));
  43189. BABYLON.TargetCamera = TargetCamera;
  43190. })(BABYLON || (BABYLON = {}));
  43191. //# sourceMappingURL=babylon.targetCamera.js.map
  43192. var BABYLON;
  43193. (function (BABYLON) {
  43194. var FreeCameraMouseInput = /** @class */ (function () {
  43195. function FreeCameraMouseInput(touchEnabled) {
  43196. if (touchEnabled === void 0) { touchEnabled = true; }
  43197. this.touchEnabled = touchEnabled;
  43198. this.buttons = [0, 1, 2];
  43199. this.angularSensibility = 2000.0;
  43200. this.previousPosition = null;
  43201. }
  43202. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43203. var _this = this;
  43204. var engine = this.camera.getEngine();
  43205. if (!this._pointerInput) {
  43206. this._pointerInput = function (p, s) {
  43207. var evt = p.event;
  43208. if (engine.isInVRExclusivePointerMode) {
  43209. return;
  43210. }
  43211. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43212. return;
  43213. }
  43214. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43215. return;
  43216. }
  43217. var srcElement = (evt.srcElement || evt.target);
  43218. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43219. try {
  43220. srcElement.setPointerCapture(evt.pointerId);
  43221. }
  43222. catch (e) {
  43223. //Nothing to do with the error. Execution will continue.
  43224. }
  43225. _this.previousPosition = {
  43226. x: evt.clientX,
  43227. y: evt.clientY
  43228. };
  43229. if (!noPreventDefault) {
  43230. evt.preventDefault();
  43231. element.focus();
  43232. }
  43233. }
  43234. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43235. try {
  43236. srcElement.releasePointerCapture(evt.pointerId);
  43237. }
  43238. catch (e) {
  43239. //Nothing to do with the error.
  43240. }
  43241. _this.previousPosition = null;
  43242. if (!noPreventDefault) {
  43243. evt.preventDefault();
  43244. }
  43245. }
  43246. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43247. if (!_this.previousPosition || engine.isPointerLock) {
  43248. return;
  43249. }
  43250. var offsetX = evt.clientX - _this.previousPosition.x;
  43251. var offsetY = evt.clientY - _this.previousPosition.y;
  43252. if (_this.camera.getScene().useRightHandedSystem) {
  43253. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43254. }
  43255. else {
  43256. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43257. }
  43258. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43259. _this.previousPosition = {
  43260. x: evt.clientX,
  43261. y: evt.clientY
  43262. };
  43263. if (!noPreventDefault) {
  43264. evt.preventDefault();
  43265. }
  43266. }
  43267. };
  43268. }
  43269. this._onMouseMove = function (evt) {
  43270. if (!engine.isPointerLock) {
  43271. return;
  43272. }
  43273. if (engine.isInVRExclusivePointerMode) {
  43274. return;
  43275. }
  43276. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43277. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43278. if (_this.camera.getScene().useRightHandedSystem) {
  43279. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43280. }
  43281. else {
  43282. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43283. }
  43284. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43285. _this.previousPosition = null;
  43286. if (!noPreventDefault) {
  43287. evt.preventDefault();
  43288. }
  43289. };
  43290. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43291. element.addEventListener("mousemove", this._onMouseMove, false);
  43292. };
  43293. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43294. if (this._observer && element) {
  43295. this.camera.getScene().onPointerObservable.remove(this._observer);
  43296. if (this._onMouseMove) {
  43297. element.removeEventListener("mousemove", this._onMouseMove);
  43298. }
  43299. this._observer = null;
  43300. this._onMouseMove = null;
  43301. this.previousPosition = null;
  43302. }
  43303. };
  43304. FreeCameraMouseInput.prototype.getClassName = function () {
  43305. return "FreeCameraMouseInput";
  43306. };
  43307. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43308. return "mouse";
  43309. };
  43310. __decorate([
  43311. BABYLON.serialize()
  43312. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43313. __decorate([
  43314. BABYLON.serialize()
  43315. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43316. return FreeCameraMouseInput;
  43317. }());
  43318. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43319. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43320. })(BABYLON || (BABYLON = {}));
  43321. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43322. var BABYLON;
  43323. (function (BABYLON) {
  43324. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43325. function FreeCameraKeyboardMoveInput() {
  43326. this._keys = new Array();
  43327. this.keysUp = [38];
  43328. this.keysDown = [40];
  43329. this.keysLeft = [37];
  43330. this.keysRight = [39];
  43331. }
  43332. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43333. var _this = this;
  43334. if (this._onCanvasBlurObserver) {
  43335. return;
  43336. }
  43337. this._scene = this.camera.getScene();
  43338. this._engine = this._scene.getEngine();
  43339. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43340. _this._keys = [];
  43341. });
  43342. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43343. var evt = info.event;
  43344. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43345. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43346. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43347. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43348. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43349. var index = _this._keys.indexOf(evt.keyCode);
  43350. if (index === -1) {
  43351. _this._keys.push(evt.keyCode);
  43352. }
  43353. if (!noPreventDefault) {
  43354. evt.preventDefault();
  43355. }
  43356. }
  43357. }
  43358. else {
  43359. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43360. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43361. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43362. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43363. var index = _this._keys.indexOf(evt.keyCode);
  43364. if (index >= 0) {
  43365. _this._keys.splice(index, 1);
  43366. }
  43367. if (!noPreventDefault) {
  43368. evt.preventDefault();
  43369. }
  43370. }
  43371. }
  43372. });
  43373. };
  43374. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43375. if (this._scene) {
  43376. if (this._onKeyboardObserver) {
  43377. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43378. }
  43379. if (this._onCanvasBlurObserver) {
  43380. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43381. }
  43382. this._onKeyboardObserver = null;
  43383. this._onCanvasBlurObserver = null;
  43384. }
  43385. this._keys = [];
  43386. };
  43387. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43388. if (this._onKeyboardObserver) {
  43389. var camera = this.camera;
  43390. // Keyboard
  43391. for (var index = 0; index < this._keys.length; index++) {
  43392. var keyCode = this._keys[index];
  43393. var speed = camera._computeLocalCameraSpeed();
  43394. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43395. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43396. }
  43397. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43398. camera._localDirection.copyFromFloats(0, 0, speed);
  43399. }
  43400. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43401. camera._localDirection.copyFromFloats(speed, 0, 0);
  43402. }
  43403. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43404. camera._localDirection.copyFromFloats(0, 0, -speed);
  43405. }
  43406. if (camera.getScene().useRightHandedSystem) {
  43407. camera._localDirection.z *= -1;
  43408. }
  43409. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43410. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43411. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43412. }
  43413. }
  43414. };
  43415. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43416. return "FreeCameraKeyboardMoveInput";
  43417. };
  43418. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43419. this._keys = [];
  43420. };
  43421. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43422. return "keyboard";
  43423. };
  43424. __decorate([
  43425. BABYLON.serialize()
  43426. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43427. __decorate([
  43428. BABYLON.serialize()
  43429. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43430. __decorate([
  43431. BABYLON.serialize()
  43432. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43433. __decorate([
  43434. BABYLON.serialize()
  43435. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43436. return FreeCameraKeyboardMoveInput;
  43437. }());
  43438. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43439. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43440. })(BABYLON || (BABYLON = {}));
  43441. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43442. var BABYLON;
  43443. (function (BABYLON) {
  43444. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43445. __extends(FreeCameraInputsManager, _super);
  43446. function FreeCameraInputsManager(camera) {
  43447. return _super.call(this, camera) || this;
  43448. }
  43449. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43450. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43451. return this;
  43452. };
  43453. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43454. if (touchEnabled === void 0) { touchEnabled = true; }
  43455. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43456. return this;
  43457. };
  43458. FreeCameraInputsManager.prototype.addGamepad = function () {
  43459. this.add(new BABYLON.FreeCameraGamepadInput());
  43460. return this;
  43461. };
  43462. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43463. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43464. return this;
  43465. };
  43466. FreeCameraInputsManager.prototype.addTouch = function () {
  43467. this.add(new BABYLON.FreeCameraTouchInput());
  43468. return this;
  43469. };
  43470. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43471. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43472. return this;
  43473. };
  43474. return FreeCameraInputsManager;
  43475. }(BABYLON.CameraInputsManager));
  43476. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43477. })(BABYLON || (BABYLON = {}));
  43478. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43479. var BABYLON;
  43480. (function (BABYLON) {
  43481. var FreeCamera = /** @class */ (function (_super) {
  43482. __extends(FreeCamera, _super);
  43483. function FreeCamera(name, position, scene) {
  43484. var _this = _super.call(this, name, position, scene) || this;
  43485. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43486. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43487. _this.checkCollisions = false;
  43488. _this.applyGravity = false;
  43489. _this._needMoveForGravity = false;
  43490. _this._oldPosition = BABYLON.Vector3.Zero();
  43491. _this._diffPosition = BABYLON.Vector3.Zero();
  43492. _this._newPosition = BABYLON.Vector3.Zero();
  43493. // Collisions
  43494. _this._collisionMask = -1;
  43495. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43496. if (collidedMesh === void 0) { collidedMesh = null; }
  43497. //TODO move this to the collision coordinator!
  43498. if (_this.getScene().workerCollisions)
  43499. newPosition.multiplyInPlace(_this._collider._radius);
  43500. var updatePosition = function (newPos) {
  43501. _this._newPosition.copyFrom(newPos);
  43502. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43503. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43504. _this.position.addInPlace(_this._diffPosition);
  43505. if (_this.onCollide && collidedMesh) {
  43506. _this.onCollide(collidedMesh);
  43507. }
  43508. }
  43509. };
  43510. updatePosition(newPosition);
  43511. };
  43512. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43513. _this.inputs.addKeyboard().addMouse();
  43514. return _this;
  43515. }
  43516. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43517. //-- begin properties for backward compatibility for inputs
  43518. /**
  43519. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43520. * Higher values reduce sensitivity.
  43521. */
  43522. get: function () {
  43523. var mouse = this.inputs.attached["mouse"];
  43524. if (mouse)
  43525. return mouse.angularSensibility;
  43526. return 0;
  43527. },
  43528. /**
  43529. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43530. * Higher values reduce sensitivity.
  43531. */
  43532. set: function (value) {
  43533. var mouse = this.inputs.attached["mouse"];
  43534. if (mouse)
  43535. mouse.angularSensibility = value;
  43536. },
  43537. enumerable: true,
  43538. configurable: true
  43539. });
  43540. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43541. get: function () {
  43542. var keyboard = this.inputs.attached["keyboard"];
  43543. if (keyboard)
  43544. return keyboard.keysUp;
  43545. return [];
  43546. },
  43547. set: function (value) {
  43548. var keyboard = this.inputs.attached["keyboard"];
  43549. if (keyboard)
  43550. keyboard.keysUp = value;
  43551. },
  43552. enumerable: true,
  43553. configurable: true
  43554. });
  43555. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43556. get: function () {
  43557. var keyboard = this.inputs.attached["keyboard"];
  43558. if (keyboard)
  43559. return keyboard.keysDown;
  43560. return [];
  43561. },
  43562. set: function (value) {
  43563. var keyboard = this.inputs.attached["keyboard"];
  43564. if (keyboard)
  43565. keyboard.keysDown = value;
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43571. get: function () {
  43572. var keyboard = this.inputs.attached["keyboard"];
  43573. if (keyboard)
  43574. return keyboard.keysLeft;
  43575. return [];
  43576. },
  43577. set: function (value) {
  43578. var keyboard = this.inputs.attached["keyboard"];
  43579. if (keyboard)
  43580. keyboard.keysLeft = value;
  43581. },
  43582. enumerable: true,
  43583. configurable: true
  43584. });
  43585. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43586. get: function () {
  43587. var keyboard = this.inputs.attached["keyboard"];
  43588. if (keyboard)
  43589. return keyboard.keysRight;
  43590. return [];
  43591. },
  43592. set: function (value) {
  43593. var keyboard = this.inputs.attached["keyboard"];
  43594. if (keyboard)
  43595. keyboard.keysRight = value;
  43596. },
  43597. enumerable: true,
  43598. configurable: true
  43599. });
  43600. // Controls
  43601. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43602. this.inputs.attachElement(element, noPreventDefault);
  43603. };
  43604. FreeCamera.prototype.detachControl = function (element) {
  43605. this.inputs.detachElement(element);
  43606. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43607. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43608. };
  43609. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43610. get: function () {
  43611. return this._collisionMask;
  43612. },
  43613. set: function (mask) {
  43614. this._collisionMask = !isNaN(mask) ? mask : -1;
  43615. },
  43616. enumerable: true,
  43617. configurable: true
  43618. });
  43619. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43620. var globalPosition;
  43621. if (this.parent) {
  43622. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43623. }
  43624. else {
  43625. globalPosition = this.position;
  43626. }
  43627. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43628. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43629. if (!this._collider) {
  43630. this._collider = new BABYLON.Collider();
  43631. }
  43632. this._collider._radius = this.ellipsoid;
  43633. this._collider.collisionMask = this._collisionMask;
  43634. //no need for clone, as long as gravity is not on.
  43635. var actualDisplacement = displacement;
  43636. //add gravity to the direction to prevent the dual-collision checking
  43637. if (this.applyGravity) {
  43638. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43639. actualDisplacement = displacement.add(this.getScene().gravity);
  43640. }
  43641. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43642. };
  43643. FreeCamera.prototype._checkInputs = function () {
  43644. if (!this._localDirection) {
  43645. this._localDirection = BABYLON.Vector3.Zero();
  43646. this._transformedDirection = BABYLON.Vector3.Zero();
  43647. }
  43648. this.inputs.checkInputs();
  43649. _super.prototype._checkInputs.call(this);
  43650. };
  43651. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43652. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43653. };
  43654. FreeCamera.prototype._updatePosition = function () {
  43655. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43656. this._collideWithWorld(this.cameraDirection);
  43657. }
  43658. else {
  43659. _super.prototype._updatePosition.call(this);
  43660. }
  43661. };
  43662. FreeCamera.prototype.dispose = function () {
  43663. this.inputs.clear();
  43664. _super.prototype.dispose.call(this);
  43665. };
  43666. FreeCamera.prototype.getClassName = function () {
  43667. return "FreeCamera";
  43668. };
  43669. __decorate([
  43670. BABYLON.serializeAsVector3()
  43671. ], FreeCamera.prototype, "ellipsoid", void 0);
  43672. __decorate([
  43673. BABYLON.serializeAsVector3()
  43674. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43675. __decorate([
  43676. BABYLON.serialize()
  43677. ], FreeCamera.prototype, "checkCollisions", void 0);
  43678. __decorate([
  43679. BABYLON.serialize()
  43680. ], FreeCamera.prototype, "applyGravity", void 0);
  43681. return FreeCamera;
  43682. }(BABYLON.TargetCamera));
  43683. BABYLON.FreeCamera = FreeCamera;
  43684. })(BABYLON || (BABYLON = {}));
  43685. //# sourceMappingURL=babylon.freeCamera.js.map
  43686. var BABYLON;
  43687. (function (BABYLON) {
  43688. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43689. function ArcRotateCameraKeyboardMoveInput() {
  43690. this._keys = new Array();
  43691. this.keysUp = [38];
  43692. this.keysDown = [40];
  43693. this.keysLeft = [37];
  43694. this.keysRight = [39];
  43695. this.keysReset = [220];
  43696. this.panningSensibility = 50.0;
  43697. this.zoomingSensibility = 25.0;
  43698. this.useAltToZoom = true;
  43699. }
  43700. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43701. var _this = this;
  43702. if (this._onCanvasBlurObserver) {
  43703. return;
  43704. }
  43705. this._scene = this.camera.getScene();
  43706. this._engine = this._scene.getEngine();
  43707. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43708. _this._keys = [];
  43709. });
  43710. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43711. var evt = info.event;
  43712. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43713. _this._ctrlPressed = evt.ctrlKey;
  43714. _this._altPressed = evt.altKey;
  43715. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43716. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43717. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43718. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43719. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43720. var index = _this._keys.indexOf(evt.keyCode);
  43721. if (index === -1) {
  43722. _this._keys.push(evt.keyCode);
  43723. }
  43724. if (evt.preventDefault) {
  43725. if (!noPreventDefault) {
  43726. evt.preventDefault();
  43727. }
  43728. }
  43729. }
  43730. }
  43731. else {
  43732. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43733. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43734. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43735. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43736. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43737. var index = _this._keys.indexOf(evt.keyCode);
  43738. if (index >= 0) {
  43739. _this._keys.splice(index, 1);
  43740. }
  43741. if (evt.preventDefault) {
  43742. if (!noPreventDefault) {
  43743. evt.preventDefault();
  43744. }
  43745. }
  43746. }
  43747. }
  43748. });
  43749. };
  43750. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43751. if (this._scene) {
  43752. if (this._onKeyboardObserver) {
  43753. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43754. }
  43755. if (this._onCanvasBlurObserver) {
  43756. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43757. }
  43758. this._onKeyboardObserver = null;
  43759. this._onCanvasBlurObserver = null;
  43760. }
  43761. this._keys = [];
  43762. };
  43763. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43764. if (this._onKeyboardObserver) {
  43765. var camera = this.camera;
  43766. for (var index = 0; index < this._keys.length; index++) {
  43767. var keyCode = this._keys[index];
  43768. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43769. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43770. camera.inertialPanningX -= 1 / this.panningSensibility;
  43771. }
  43772. else {
  43773. camera.inertialAlphaOffset -= 0.01;
  43774. }
  43775. }
  43776. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43777. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43778. camera.inertialPanningY += 1 / this.panningSensibility;
  43779. }
  43780. else if (this._altPressed && this.useAltToZoom) {
  43781. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43782. }
  43783. else {
  43784. camera.inertialBetaOffset -= 0.01;
  43785. }
  43786. }
  43787. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43788. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43789. camera.inertialPanningX += 1 / this.panningSensibility;
  43790. }
  43791. else {
  43792. camera.inertialAlphaOffset += 0.01;
  43793. }
  43794. }
  43795. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43796. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43797. camera.inertialPanningY -= 1 / this.panningSensibility;
  43798. }
  43799. else if (this._altPressed && this.useAltToZoom) {
  43800. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43801. }
  43802. else {
  43803. camera.inertialBetaOffset += 0.01;
  43804. }
  43805. }
  43806. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43807. camera.restoreState();
  43808. }
  43809. }
  43810. }
  43811. };
  43812. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43813. return "ArcRotateCameraKeyboardMoveInput";
  43814. };
  43815. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43816. return "keyboard";
  43817. };
  43818. __decorate([
  43819. BABYLON.serialize()
  43820. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43821. __decorate([
  43822. BABYLON.serialize()
  43823. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43824. __decorate([
  43825. BABYLON.serialize()
  43826. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43827. __decorate([
  43828. BABYLON.serialize()
  43829. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43830. __decorate([
  43831. BABYLON.serialize()
  43832. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43833. __decorate([
  43834. BABYLON.serialize()
  43835. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43836. __decorate([
  43837. BABYLON.serialize()
  43838. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43839. __decorate([
  43840. BABYLON.serialize()
  43841. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43842. return ArcRotateCameraKeyboardMoveInput;
  43843. }());
  43844. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43845. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43846. })(BABYLON || (BABYLON = {}));
  43847. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43848. var BABYLON;
  43849. (function (BABYLON) {
  43850. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43851. function ArcRotateCameraMouseWheelInput() {
  43852. this.wheelPrecision = 3.0;
  43853. /**
  43854. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43855. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43856. */
  43857. this.wheelDeltaPercentage = 0;
  43858. }
  43859. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43860. var _this = this;
  43861. this._wheel = function (p, s) {
  43862. //sanity check - this should be a PointerWheel event.
  43863. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43864. return;
  43865. var event = p.event;
  43866. var delta = 0;
  43867. if (event.wheelDelta) {
  43868. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43869. }
  43870. else if (event.detail) {
  43871. delta = -event.detail / _this.wheelPrecision;
  43872. }
  43873. if (delta)
  43874. _this.camera.inertialRadiusOffset += delta;
  43875. if (event.preventDefault) {
  43876. if (!noPreventDefault) {
  43877. event.preventDefault();
  43878. }
  43879. }
  43880. };
  43881. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43882. };
  43883. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43884. if (this._observer && element) {
  43885. this.camera.getScene().onPointerObservable.remove(this._observer);
  43886. this._observer = null;
  43887. this._wheel = null;
  43888. }
  43889. };
  43890. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43891. return "ArcRotateCameraMouseWheelInput";
  43892. };
  43893. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43894. return "mousewheel";
  43895. };
  43896. __decorate([
  43897. BABYLON.serialize()
  43898. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43899. __decorate([
  43900. BABYLON.serialize()
  43901. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43902. return ArcRotateCameraMouseWheelInput;
  43903. }());
  43904. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43905. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43906. })(BABYLON || (BABYLON = {}));
  43907. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43908. var BABYLON;
  43909. (function (BABYLON) {
  43910. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43911. function ArcRotateCameraPointersInput() {
  43912. this.buttons = [0, 1, 2];
  43913. this.angularSensibilityX = 1000.0;
  43914. this.angularSensibilityY = 1000.0;
  43915. this.pinchPrecision = 12.0;
  43916. /**
  43917. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43918. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43919. */
  43920. this.pinchDeltaPercentage = 0;
  43921. this.panningSensibility = 1000.0;
  43922. this.multiTouchPanning = true;
  43923. this.multiTouchPanAndZoom = true;
  43924. this._isPanClick = false;
  43925. this.pinchInwards = true;
  43926. }
  43927. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43928. var _this = this;
  43929. var engine = this.camera.getEngine();
  43930. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43931. var pointA = null;
  43932. var pointB = null;
  43933. var previousPinchSquaredDistance = 0;
  43934. var initialDistance = 0;
  43935. var twoFingerActivityCount = 0;
  43936. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43937. this._pointerInput = function (p, s) {
  43938. var evt = p.event;
  43939. var isTouch = p.event.pointerType === "touch";
  43940. if (engine.isInVRExclusivePointerMode) {
  43941. return;
  43942. }
  43943. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43944. return;
  43945. }
  43946. var srcElement = (evt.srcElement || evt.target);
  43947. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43948. try {
  43949. srcElement.setPointerCapture(evt.pointerId);
  43950. }
  43951. catch (e) {
  43952. //Nothing to do with the error. Execution will continue.
  43953. }
  43954. // Manage panning with pan button click
  43955. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43956. // manage pointers
  43957. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43958. if (pointA === null) {
  43959. pointA = cacheSoloPointer;
  43960. }
  43961. else if (pointB === null) {
  43962. pointB = cacheSoloPointer;
  43963. }
  43964. if (!noPreventDefault) {
  43965. evt.preventDefault();
  43966. element.focus();
  43967. }
  43968. }
  43969. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43970. _this.camera.restoreState();
  43971. }
  43972. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43973. try {
  43974. srcElement.releasePointerCapture(evt.pointerId);
  43975. }
  43976. catch (e) {
  43977. //Nothing to do with the error.
  43978. }
  43979. cacheSoloPointer = null;
  43980. previousPinchSquaredDistance = 0;
  43981. previousMultiTouchPanPosition.isPaning = false;
  43982. previousMultiTouchPanPosition.isPinching = false;
  43983. twoFingerActivityCount = 0;
  43984. initialDistance = 0;
  43985. if (!isTouch) {
  43986. pointB = null; // Mouse and pen are mono pointer
  43987. }
  43988. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43989. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43990. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43991. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43992. if (engine.badOS) {
  43993. pointA = pointB = null;
  43994. }
  43995. else {
  43996. //only remove the impacted pointer in case of multitouch allowing on most
  43997. //platforms switching from rotate to zoom and pan seamlessly.
  43998. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43999. pointA = pointB;
  44000. pointB = null;
  44001. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44002. }
  44003. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44004. pointB = null;
  44005. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44006. }
  44007. else {
  44008. pointA = pointB = null;
  44009. }
  44010. }
  44011. if (!noPreventDefault) {
  44012. evt.preventDefault();
  44013. }
  44014. }
  44015. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44016. if (!noPreventDefault) {
  44017. evt.preventDefault();
  44018. }
  44019. // One button down
  44020. if (pointA && pointB === null && cacheSoloPointer) {
  44021. if (_this.panningSensibility !== 0 &&
  44022. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44023. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44024. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44025. }
  44026. else {
  44027. var offsetX = evt.clientX - cacheSoloPointer.x;
  44028. var offsetY = evt.clientY - cacheSoloPointer.y;
  44029. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44030. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44031. }
  44032. cacheSoloPointer.x = evt.clientX;
  44033. cacheSoloPointer.y = evt.clientY;
  44034. }
  44035. else if (pointA && pointB) {
  44036. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44037. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44038. ed.x = evt.clientX;
  44039. ed.y = evt.clientY;
  44040. var direction = _this.pinchInwards ? 1 : -1;
  44041. var distX = pointA.x - pointB.x;
  44042. var distY = pointA.y - pointB.y;
  44043. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44044. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44045. if (previousPinchSquaredDistance === 0) {
  44046. initialDistance = pinchDistance;
  44047. previousPinchSquaredDistance = pinchSquaredDistance;
  44048. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44049. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44050. return;
  44051. }
  44052. if (_this.multiTouchPanAndZoom) {
  44053. if (_this.pinchDeltaPercentage) {
  44054. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44055. }
  44056. else {
  44057. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44058. (_this.pinchPrecision *
  44059. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44060. direction);
  44061. }
  44062. if (_this.panningSensibility !== 0) {
  44063. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44064. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44065. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44066. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44067. previousMultiTouchPanPosition.x = pointersCenterX;
  44068. previousMultiTouchPanPosition.y = pointersCenterY;
  44069. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44070. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44071. }
  44072. }
  44073. else {
  44074. twoFingerActivityCount++;
  44075. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44076. if (_this.pinchDeltaPercentage) {
  44077. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44078. }
  44079. else {
  44080. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44081. (_this.pinchPrecision *
  44082. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44083. direction);
  44084. }
  44085. previousMultiTouchPanPosition.isPaning = false;
  44086. previousMultiTouchPanPosition.isPinching = true;
  44087. }
  44088. else {
  44089. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44090. if (!previousMultiTouchPanPosition.isPaning) {
  44091. previousMultiTouchPanPosition.isPaning = true;
  44092. previousMultiTouchPanPosition.isPinching = false;
  44093. previousMultiTouchPanPosition.x = ed.x;
  44094. previousMultiTouchPanPosition.y = ed.y;
  44095. return;
  44096. }
  44097. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44098. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44099. }
  44100. }
  44101. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44102. previousMultiTouchPanPosition.x = ed.x;
  44103. previousMultiTouchPanPosition.y = ed.y;
  44104. }
  44105. }
  44106. previousPinchSquaredDistance = pinchSquaredDistance;
  44107. }
  44108. }
  44109. };
  44110. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44111. this._onContextMenu = function (evt) {
  44112. evt.preventDefault();
  44113. };
  44114. if (!this.camera._useCtrlForPanning) {
  44115. element.addEventListener("contextmenu", this._onContextMenu, false);
  44116. }
  44117. this._onLostFocus = function () {
  44118. //this._keys = [];
  44119. pointA = pointB = null;
  44120. previousPinchSquaredDistance = 0;
  44121. previousMultiTouchPanPosition.isPaning = false;
  44122. previousMultiTouchPanPosition.isPinching = false;
  44123. twoFingerActivityCount = 0;
  44124. cacheSoloPointer = null;
  44125. initialDistance = 0;
  44126. };
  44127. this._onMouseMove = function (evt) {
  44128. if (!engine.isPointerLock) {
  44129. return;
  44130. }
  44131. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44132. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44133. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44134. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44135. if (!noPreventDefault) {
  44136. evt.preventDefault();
  44137. }
  44138. };
  44139. this._onGestureStart = function (e) {
  44140. if (window.MSGesture === undefined) {
  44141. return;
  44142. }
  44143. if (!_this._MSGestureHandler) {
  44144. _this._MSGestureHandler = new MSGesture();
  44145. _this._MSGestureHandler.target = element;
  44146. }
  44147. _this._MSGestureHandler.addPointer(e.pointerId);
  44148. };
  44149. this._onGesture = function (e) {
  44150. _this.camera.radius *= e.scale;
  44151. if (e.preventDefault) {
  44152. if (!noPreventDefault) {
  44153. e.stopPropagation();
  44154. e.preventDefault();
  44155. }
  44156. }
  44157. };
  44158. element.addEventListener("mousemove", this._onMouseMove, false);
  44159. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44160. element.addEventListener("MSGestureChange", this._onGesture, false);
  44161. BABYLON.Tools.RegisterTopRootEvents([
  44162. { name: "blur", handler: this._onLostFocus }
  44163. ]);
  44164. };
  44165. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44166. if (this._onLostFocus) {
  44167. BABYLON.Tools.UnregisterTopRootEvents([
  44168. { name: "blur", handler: this._onLostFocus }
  44169. ]);
  44170. }
  44171. if (element && this._observer) {
  44172. this.camera.getScene().onPointerObservable.remove(this._observer);
  44173. this._observer = null;
  44174. if (this._onContextMenu) {
  44175. element.removeEventListener("contextmenu", this._onContextMenu);
  44176. }
  44177. if (this._onMouseMove) {
  44178. element.removeEventListener("mousemove", this._onMouseMove);
  44179. }
  44180. if (this._onGestureStart) {
  44181. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44182. }
  44183. if (this._onGesture) {
  44184. element.removeEventListener("MSGestureChange", this._onGesture);
  44185. }
  44186. this._isPanClick = false;
  44187. this.pinchInwards = true;
  44188. this._onMouseMove = null;
  44189. this._onGestureStart = null;
  44190. this._onGesture = null;
  44191. this._MSGestureHandler = null;
  44192. this._onLostFocus = null;
  44193. this._onContextMenu = null;
  44194. }
  44195. };
  44196. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44197. return "ArcRotateCameraPointersInput";
  44198. };
  44199. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44200. return "pointers";
  44201. };
  44202. __decorate([
  44203. BABYLON.serialize()
  44204. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44205. __decorate([
  44206. BABYLON.serialize()
  44207. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44208. __decorate([
  44209. BABYLON.serialize()
  44210. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44211. __decorate([
  44212. BABYLON.serialize()
  44213. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44214. __decorate([
  44215. BABYLON.serialize()
  44216. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44217. __decorate([
  44218. BABYLON.serialize()
  44219. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44220. __decorate([
  44221. BABYLON.serialize()
  44222. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44223. __decorate([
  44224. BABYLON.serialize()
  44225. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44226. return ArcRotateCameraPointersInput;
  44227. }());
  44228. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44229. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44230. })(BABYLON || (BABYLON = {}));
  44231. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44232. var BABYLON;
  44233. (function (BABYLON) {
  44234. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44235. __extends(ArcRotateCameraInputsManager, _super);
  44236. function ArcRotateCameraInputsManager(camera) {
  44237. return _super.call(this, camera) || this;
  44238. }
  44239. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44240. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44241. return this;
  44242. };
  44243. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44244. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44245. return this;
  44246. };
  44247. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44248. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44249. return this;
  44250. };
  44251. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44252. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44253. return this;
  44254. };
  44255. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44256. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44257. return this;
  44258. };
  44259. return ArcRotateCameraInputsManager;
  44260. }(BABYLON.CameraInputsManager));
  44261. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44262. })(BABYLON || (BABYLON = {}));
  44263. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44264. var BABYLON;
  44265. (function (BABYLON) {
  44266. var ArcRotateCamera = /** @class */ (function (_super) {
  44267. __extends(ArcRotateCamera, _super);
  44268. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44269. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44270. _this.inertialAlphaOffset = 0;
  44271. _this.inertialBetaOffset = 0;
  44272. _this.inertialRadiusOffset = 0;
  44273. _this.lowerAlphaLimit = null;
  44274. _this.upperAlphaLimit = null;
  44275. _this.lowerBetaLimit = 0.01;
  44276. _this.upperBetaLimit = Math.PI;
  44277. _this.lowerRadiusLimit = null;
  44278. _this.upperRadiusLimit = null;
  44279. _this.inertialPanningX = 0;
  44280. _this.inertialPanningY = 0;
  44281. _this.pinchToPanMaxDistance = 20;
  44282. _this.panningDistanceLimit = null;
  44283. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44284. _this.panningInertia = 0.9;
  44285. //-- end properties for backward compatibility for inputs
  44286. _this.zoomOnFactor = 1;
  44287. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44288. _this.allowUpsideDown = true;
  44289. _this._viewMatrix = new BABYLON.Matrix();
  44290. // Panning
  44291. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44292. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44293. _this.checkCollisions = false;
  44294. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44295. _this._previousPosition = BABYLON.Vector3.Zero();
  44296. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44297. _this._newPosition = BABYLON.Vector3.Zero();
  44298. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44299. if (collidedMesh === void 0) { collidedMesh = null; }
  44300. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44301. newPosition.multiplyInPlace(_this._collider._radius);
  44302. }
  44303. if (!collidedMesh) {
  44304. _this._previousPosition.copyFrom(_this.position);
  44305. }
  44306. else {
  44307. _this.setPosition(newPosition);
  44308. if (_this.onCollide) {
  44309. _this.onCollide(collidedMesh);
  44310. }
  44311. }
  44312. // Recompute because of constraints
  44313. var cosa = Math.cos(_this.alpha);
  44314. var sina = Math.sin(_this.alpha);
  44315. var cosb = Math.cos(_this.beta);
  44316. var sinb = Math.sin(_this.beta);
  44317. if (sinb === 0) {
  44318. sinb = 0.0001;
  44319. }
  44320. var target = _this._getTargetPosition();
  44321. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44322. _this.position.copyFrom(_this._newPosition);
  44323. var up = _this.upVector;
  44324. if (_this.allowUpsideDown && _this.beta < 0) {
  44325. up = up.clone();
  44326. up = up.negate();
  44327. }
  44328. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44329. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44330. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44331. _this._collisionTriggered = false;
  44332. };
  44333. _this._target = BABYLON.Vector3.Zero();
  44334. if (target) {
  44335. _this.setTarget(target);
  44336. }
  44337. _this.alpha = alpha;
  44338. _this.beta = beta;
  44339. _this.radius = radius;
  44340. _this.getViewMatrix();
  44341. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44342. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44343. return _this;
  44344. }
  44345. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44346. get: function () {
  44347. return this._target;
  44348. },
  44349. set: function (value) {
  44350. this.setTarget(value);
  44351. },
  44352. enumerable: true,
  44353. configurable: true
  44354. });
  44355. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44356. //-- begin properties for backward compatibility for inputs
  44357. get: function () {
  44358. var pointers = this.inputs.attached["pointers"];
  44359. if (pointers)
  44360. return pointers.angularSensibilityX;
  44361. return 0;
  44362. },
  44363. set: function (value) {
  44364. var pointers = this.inputs.attached["pointers"];
  44365. if (pointers) {
  44366. pointers.angularSensibilityX = value;
  44367. }
  44368. },
  44369. enumerable: true,
  44370. configurable: true
  44371. });
  44372. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44373. get: function () {
  44374. var pointers = this.inputs.attached["pointers"];
  44375. if (pointers)
  44376. return pointers.angularSensibilityY;
  44377. return 0;
  44378. },
  44379. set: function (value) {
  44380. var pointers = this.inputs.attached["pointers"];
  44381. if (pointers) {
  44382. pointers.angularSensibilityY = value;
  44383. }
  44384. },
  44385. enumerable: true,
  44386. configurable: true
  44387. });
  44388. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44389. get: function () {
  44390. var pointers = this.inputs.attached["pointers"];
  44391. if (pointers)
  44392. return pointers.pinchPrecision;
  44393. return 0;
  44394. },
  44395. set: function (value) {
  44396. var pointers = this.inputs.attached["pointers"];
  44397. if (pointers) {
  44398. pointers.pinchPrecision = value;
  44399. }
  44400. },
  44401. enumerable: true,
  44402. configurable: true
  44403. });
  44404. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44405. get: function () {
  44406. var pointers = this.inputs.attached["pointers"];
  44407. if (pointers)
  44408. return pointers.pinchDeltaPercentage;
  44409. return 0;
  44410. },
  44411. set: function (value) {
  44412. var pointers = this.inputs.attached["pointers"];
  44413. if (pointers) {
  44414. pointers.pinchDeltaPercentage = value;
  44415. }
  44416. },
  44417. enumerable: true,
  44418. configurable: true
  44419. });
  44420. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44421. get: function () {
  44422. var pointers = this.inputs.attached["pointers"];
  44423. if (pointers)
  44424. return pointers.panningSensibility;
  44425. return 0;
  44426. },
  44427. set: function (value) {
  44428. var pointers = this.inputs.attached["pointers"];
  44429. if (pointers) {
  44430. pointers.panningSensibility = value;
  44431. }
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44437. get: function () {
  44438. var keyboard = this.inputs.attached["keyboard"];
  44439. if (keyboard)
  44440. return keyboard.keysUp;
  44441. return [];
  44442. },
  44443. set: function (value) {
  44444. var keyboard = this.inputs.attached["keyboard"];
  44445. if (keyboard)
  44446. keyboard.keysUp = value;
  44447. },
  44448. enumerable: true,
  44449. configurable: true
  44450. });
  44451. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44452. get: function () {
  44453. var keyboard = this.inputs.attached["keyboard"];
  44454. if (keyboard)
  44455. return keyboard.keysDown;
  44456. return [];
  44457. },
  44458. set: function (value) {
  44459. var keyboard = this.inputs.attached["keyboard"];
  44460. if (keyboard)
  44461. keyboard.keysDown = value;
  44462. },
  44463. enumerable: true,
  44464. configurable: true
  44465. });
  44466. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44467. get: function () {
  44468. var keyboard = this.inputs.attached["keyboard"];
  44469. if (keyboard)
  44470. return keyboard.keysLeft;
  44471. return [];
  44472. },
  44473. set: function (value) {
  44474. var keyboard = this.inputs.attached["keyboard"];
  44475. if (keyboard)
  44476. keyboard.keysLeft = value;
  44477. },
  44478. enumerable: true,
  44479. configurable: true
  44480. });
  44481. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44482. get: function () {
  44483. var keyboard = this.inputs.attached["keyboard"];
  44484. if (keyboard)
  44485. return keyboard.keysRight;
  44486. return [];
  44487. },
  44488. set: function (value) {
  44489. var keyboard = this.inputs.attached["keyboard"];
  44490. if (keyboard)
  44491. keyboard.keysRight = value;
  44492. },
  44493. enumerable: true,
  44494. configurable: true
  44495. });
  44496. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44497. get: function () {
  44498. var mousewheel = this.inputs.attached["mousewheel"];
  44499. if (mousewheel)
  44500. return mousewheel.wheelPrecision;
  44501. return 0;
  44502. },
  44503. set: function (value) {
  44504. var mousewheel = this.inputs.attached["mousewheel"];
  44505. if (mousewheel)
  44506. mousewheel.wheelPrecision = value;
  44507. },
  44508. enumerable: true,
  44509. configurable: true
  44510. });
  44511. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44512. get: function () {
  44513. var mousewheel = this.inputs.attached["mousewheel"];
  44514. if (mousewheel)
  44515. return mousewheel.wheelDeltaPercentage;
  44516. return 0;
  44517. },
  44518. set: function (value) {
  44519. var mousewheel = this.inputs.attached["mousewheel"];
  44520. if (mousewheel)
  44521. mousewheel.wheelDeltaPercentage = value;
  44522. },
  44523. enumerable: true,
  44524. configurable: true
  44525. });
  44526. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44527. get: function () {
  44528. return this._bouncingBehavior;
  44529. },
  44530. enumerable: true,
  44531. configurable: true
  44532. });
  44533. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44534. get: function () {
  44535. return this._bouncingBehavior != null;
  44536. },
  44537. set: function (value) {
  44538. if (value === this.useBouncingBehavior) {
  44539. return;
  44540. }
  44541. if (value) {
  44542. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44543. this.addBehavior(this._bouncingBehavior);
  44544. }
  44545. else if (this._bouncingBehavior) {
  44546. this.removeBehavior(this._bouncingBehavior);
  44547. this._bouncingBehavior = null;
  44548. }
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44554. get: function () {
  44555. return this._framingBehavior;
  44556. },
  44557. enumerable: true,
  44558. configurable: true
  44559. });
  44560. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44561. get: function () {
  44562. return this._framingBehavior != null;
  44563. },
  44564. set: function (value) {
  44565. if (value === this.useFramingBehavior) {
  44566. return;
  44567. }
  44568. if (value) {
  44569. this._framingBehavior = new BABYLON.FramingBehavior();
  44570. this.addBehavior(this._framingBehavior);
  44571. }
  44572. else if (this._framingBehavior) {
  44573. this.removeBehavior(this._framingBehavior);
  44574. this._framingBehavior = null;
  44575. }
  44576. },
  44577. enumerable: true,
  44578. configurable: true
  44579. });
  44580. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44581. get: function () {
  44582. return this._autoRotationBehavior;
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44588. get: function () {
  44589. return this._autoRotationBehavior != null;
  44590. },
  44591. set: function (value) {
  44592. if (value === this.useAutoRotationBehavior) {
  44593. return;
  44594. }
  44595. if (value) {
  44596. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44597. this.addBehavior(this._autoRotationBehavior);
  44598. }
  44599. else if (this._autoRotationBehavior) {
  44600. this.removeBehavior(this._autoRotationBehavior);
  44601. this._autoRotationBehavior = null;
  44602. }
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. // Cache
  44608. ArcRotateCamera.prototype._initCache = function () {
  44609. _super.prototype._initCache.call(this);
  44610. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44611. this._cache.alpha = undefined;
  44612. this._cache.beta = undefined;
  44613. this._cache.radius = undefined;
  44614. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44615. };
  44616. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44617. if (!ignoreParentClass) {
  44618. _super.prototype._updateCache.call(this);
  44619. }
  44620. this._cache._target.copyFrom(this._getTargetPosition());
  44621. this._cache.alpha = this.alpha;
  44622. this._cache.beta = this.beta;
  44623. this._cache.radius = this.radius;
  44624. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44625. };
  44626. ArcRotateCamera.prototype._getTargetPosition = function () {
  44627. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44628. var pos = this._targetHost.getAbsolutePosition();
  44629. if (this._targetBoundingCenter) {
  44630. pos.addToRef(this._targetBoundingCenter, this._target);
  44631. }
  44632. else {
  44633. this._target.copyFrom(pos);
  44634. }
  44635. }
  44636. var lockedTargetPosition = this._getLockedTargetPosition();
  44637. if (lockedTargetPosition) {
  44638. return lockedTargetPosition;
  44639. }
  44640. return this._target;
  44641. };
  44642. ArcRotateCamera.prototype.storeState = function () {
  44643. this._storedAlpha = this.alpha;
  44644. this._storedBeta = this.beta;
  44645. this._storedRadius = this.radius;
  44646. this._storedTarget = this._getTargetPosition().clone();
  44647. return _super.prototype.storeState.call(this);
  44648. };
  44649. /**
  44650. * Restored camera state. You must call storeState() first
  44651. */
  44652. ArcRotateCamera.prototype._restoreStateValues = function () {
  44653. if (!_super.prototype._restoreStateValues.call(this)) {
  44654. return false;
  44655. }
  44656. this.alpha = this._storedAlpha;
  44657. this.beta = this._storedBeta;
  44658. this.radius = this._storedRadius;
  44659. this.setTarget(this._storedTarget.clone());
  44660. this.inertialAlphaOffset = 0;
  44661. this.inertialBetaOffset = 0;
  44662. this.inertialRadiusOffset = 0;
  44663. this.inertialPanningX = 0;
  44664. this.inertialPanningY = 0;
  44665. return true;
  44666. };
  44667. // Synchronized
  44668. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44669. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44670. return false;
  44671. return this._cache._target.equals(this._getTargetPosition())
  44672. && this._cache.alpha === this.alpha
  44673. && this._cache.beta === this.beta
  44674. && this._cache.radius === this.radius
  44675. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44676. };
  44677. // Methods
  44678. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44679. var _this = this;
  44680. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44681. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44682. this._useCtrlForPanning = useCtrlForPanning;
  44683. this._panningMouseButton = panningMouseButton;
  44684. this.inputs.attachElement(element, noPreventDefault);
  44685. this._reset = function () {
  44686. _this.inertialAlphaOffset = 0;
  44687. _this.inertialBetaOffset = 0;
  44688. _this.inertialRadiusOffset = 0;
  44689. _this.inertialPanningX = 0;
  44690. _this.inertialPanningY = 0;
  44691. };
  44692. };
  44693. ArcRotateCamera.prototype.detachControl = function (element) {
  44694. this.inputs.detachElement(element);
  44695. if (this._reset) {
  44696. this._reset();
  44697. }
  44698. };
  44699. ArcRotateCamera.prototype._checkInputs = function () {
  44700. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44701. if (this._collisionTriggered) {
  44702. return;
  44703. }
  44704. this.inputs.checkInputs();
  44705. // Inertia
  44706. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44707. if (this.getScene().useRightHandedSystem) {
  44708. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44709. }
  44710. else {
  44711. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44712. }
  44713. this.beta += this.inertialBetaOffset;
  44714. this.radius -= this.inertialRadiusOffset;
  44715. this.inertialAlphaOffset *= this.inertia;
  44716. this.inertialBetaOffset *= this.inertia;
  44717. this.inertialRadiusOffset *= this.inertia;
  44718. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44719. this.inertialAlphaOffset = 0;
  44720. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44721. this.inertialBetaOffset = 0;
  44722. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44723. this.inertialRadiusOffset = 0;
  44724. }
  44725. // Panning inertia
  44726. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44727. if (!this._localDirection) {
  44728. this._localDirection = BABYLON.Vector3.Zero();
  44729. this._transformedDirection = BABYLON.Vector3.Zero();
  44730. }
  44731. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44732. this._localDirection.multiplyInPlace(this.panningAxis);
  44733. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44734. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44735. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44736. if (!this.panningAxis.y) {
  44737. this._transformedDirection.y = 0;
  44738. }
  44739. if (!this._targetHost) {
  44740. if (this.panningDistanceLimit) {
  44741. this._transformedDirection.addInPlace(this._target);
  44742. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44743. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44744. this._target.copyFrom(this._transformedDirection);
  44745. }
  44746. }
  44747. else {
  44748. this._target.addInPlace(this._transformedDirection);
  44749. }
  44750. }
  44751. this.inertialPanningX *= this.panningInertia;
  44752. this.inertialPanningY *= this.panningInertia;
  44753. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44754. this.inertialPanningX = 0;
  44755. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44756. this.inertialPanningY = 0;
  44757. }
  44758. // Limits
  44759. this._checkLimits();
  44760. _super.prototype._checkInputs.call(this);
  44761. };
  44762. ArcRotateCamera.prototype._checkLimits = function () {
  44763. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44764. if (this.allowUpsideDown && this.beta > Math.PI) {
  44765. this.beta = this.beta - (2 * Math.PI);
  44766. }
  44767. }
  44768. else {
  44769. if (this.beta < this.lowerBetaLimit) {
  44770. this.beta = this.lowerBetaLimit;
  44771. }
  44772. }
  44773. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44774. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44775. this.beta = this.beta + (2 * Math.PI);
  44776. }
  44777. }
  44778. else {
  44779. if (this.beta > this.upperBetaLimit) {
  44780. this.beta = this.upperBetaLimit;
  44781. }
  44782. }
  44783. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44784. this.alpha = this.lowerAlphaLimit;
  44785. }
  44786. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44787. this.alpha = this.upperAlphaLimit;
  44788. }
  44789. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44790. this.radius = this.lowerRadiusLimit;
  44791. }
  44792. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44793. this.radius = this.upperRadiusLimit;
  44794. }
  44795. };
  44796. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44797. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44798. this.radius = radiusv3.length();
  44799. if (this.radius === 0) {
  44800. this.radius = 0.0001; // Just to avoid division by zero
  44801. }
  44802. // Alpha
  44803. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44804. if (radiusv3.z < 0) {
  44805. this.alpha = 2 * Math.PI - this.alpha;
  44806. }
  44807. // Beta
  44808. this.beta = Math.acos(radiusv3.y / this.radius);
  44809. this._checkLimits();
  44810. };
  44811. ArcRotateCamera.prototype.setPosition = function (position) {
  44812. if (this.position.equals(position)) {
  44813. return;
  44814. }
  44815. this.position.copyFrom(position);
  44816. this.rebuildAnglesAndRadius();
  44817. };
  44818. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44819. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44820. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44821. if (target.getBoundingInfo) {
  44822. if (toBoundingCenter) {
  44823. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44824. }
  44825. else {
  44826. this._targetBoundingCenter = null;
  44827. }
  44828. this._targetHost = target;
  44829. this._target = this._getTargetPosition();
  44830. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44831. }
  44832. else {
  44833. var newTarget = target;
  44834. var currentTarget = this._getTargetPosition();
  44835. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44836. return;
  44837. }
  44838. this._targetHost = null;
  44839. this._target = newTarget;
  44840. this._targetBoundingCenter = null;
  44841. this.onMeshTargetChangedObservable.notifyObservers(null);
  44842. }
  44843. this.rebuildAnglesAndRadius();
  44844. };
  44845. ArcRotateCamera.prototype._getViewMatrix = function () {
  44846. // Compute
  44847. var cosa = Math.cos(this.alpha);
  44848. var sina = Math.sin(this.alpha);
  44849. var cosb = Math.cos(this.beta);
  44850. var sinb = Math.sin(this.beta);
  44851. if (sinb === 0) {
  44852. sinb = 0.0001;
  44853. }
  44854. var target = this._getTargetPosition();
  44855. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44856. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44857. if (!this._collider) {
  44858. this._collider = new BABYLON.Collider();
  44859. }
  44860. this._collider._radius = this.collisionRadius;
  44861. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44862. this._collisionTriggered = true;
  44863. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44864. }
  44865. else {
  44866. this.position.copyFrom(this._newPosition);
  44867. var up = this.upVector;
  44868. if (this.allowUpsideDown && sinb < 0) {
  44869. up = up.clone();
  44870. up = up.negate();
  44871. }
  44872. if (this.getScene().useRightHandedSystem) {
  44873. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44874. }
  44875. else {
  44876. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44877. }
  44878. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44879. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44880. }
  44881. this._currentTarget = target;
  44882. return this._viewMatrix;
  44883. };
  44884. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44885. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44886. meshes = meshes || this.getScene().meshes;
  44887. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44888. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44889. this.radius = distance * this.zoomOnFactor;
  44890. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44891. };
  44892. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44893. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44894. var meshesOrMinMaxVector;
  44895. var distance;
  44896. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44897. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44898. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44899. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44900. }
  44901. else {
  44902. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44903. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44904. distance = minMaxVectorAndDistance.distance;
  44905. }
  44906. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44907. if (!doNotUpdateMaxZ) {
  44908. this.maxZ = distance * 2;
  44909. }
  44910. };
  44911. /**
  44912. * @override
  44913. * Override Camera.createRigCamera
  44914. */
  44915. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44916. var alphaShift = 0;
  44917. switch (this.cameraRigMode) {
  44918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44921. case BABYLON.Camera.RIG_MODE_VR:
  44922. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44923. break;
  44924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44925. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44926. break;
  44927. }
  44928. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44929. rigCam._cameraRigParams = {};
  44930. return rigCam;
  44931. };
  44932. /**
  44933. * @override
  44934. * Override Camera._updateRigCameras
  44935. */
  44936. ArcRotateCamera.prototype._updateRigCameras = function () {
  44937. var camLeft = this._rigCameras[0];
  44938. var camRight = this._rigCameras[1];
  44939. camLeft.beta = camRight.beta = this.beta;
  44940. camLeft.radius = camRight.radius = this.radius;
  44941. switch (this.cameraRigMode) {
  44942. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44943. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44944. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44945. case BABYLON.Camera.RIG_MODE_VR:
  44946. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44947. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44948. break;
  44949. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44950. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44951. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44952. break;
  44953. }
  44954. _super.prototype._updateRigCameras.call(this);
  44955. };
  44956. ArcRotateCamera.prototype.dispose = function () {
  44957. this.inputs.clear();
  44958. _super.prototype.dispose.call(this);
  44959. };
  44960. ArcRotateCamera.prototype.getClassName = function () {
  44961. return "ArcRotateCamera";
  44962. };
  44963. __decorate([
  44964. BABYLON.serialize()
  44965. ], ArcRotateCamera.prototype, "alpha", void 0);
  44966. __decorate([
  44967. BABYLON.serialize()
  44968. ], ArcRotateCamera.prototype, "beta", void 0);
  44969. __decorate([
  44970. BABYLON.serialize()
  44971. ], ArcRotateCamera.prototype, "radius", void 0);
  44972. __decorate([
  44973. BABYLON.serializeAsVector3("target")
  44974. ], ArcRotateCamera.prototype, "_target", void 0);
  44975. __decorate([
  44976. BABYLON.serialize()
  44977. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44978. __decorate([
  44979. BABYLON.serialize()
  44980. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44981. __decorate([
  44982. BABYLON.serialize()
  44983. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44984. __decorate([
  44985. BABYLON.serialize()
  44986. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44987. __decorate([
  44988. BABYLON.serialize()
  44989. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44990. __decorate([
  44991. BABYLON.serialize()
  44992. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44993. __decorate([
  44994. BABYLON.serialize()
  44995. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44996. __decorate([
  44997. BABYLON.serialize()
  44998. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44999. __decorate([
  45000. BABYLON.serialize()
  45001. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45002. __decorate([
  45003. BABYLON.serialize()
  45004. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45005. __decorate([
  45006. BABYLON.serialize()
  45007. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45008. __decorate([
  45009. BABYLON.serialize()
  45010. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45011. __decorate([
  45012. BABYLON.serialize()
  45013. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45014. __decorate([
  45015. BABYLON.serializeAsVector3()
  45016. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45017. __decorate([
  45018. BABYLON.serialize()
  45019. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45020. __decorate([
  45021. BABYLON.serialize()
  45022. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45023. __decorate([
  45024. BABYLON.serialize()
  45025. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45026. return ArcRotateCamera;
  45027. }(BABYLON.TargetCamera));
  45028. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45029. })(BABYLON || (BABYLON = {}));
  45030. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45031. var BABYLON;
  45032. (function (BABYLON) {
  45033. /**
  45034. * The HemisphericLight simulates the ambient environment light,
  45035. * so the passed direction is the light reflection direction, not the incoming direction.
  45036. */
  45037. var HemisphericLight = /** @class */ (function (_super) {
  45038. __extends(HemisphericLight, _super);
  45039. /**
  45040. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45041. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45042. * The HemisphericLight can't cast shadows.
  45043. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45044. * @param name The friendly name of the light
  45045. * @param direction The direction of the light reflection
  45046. * @param scene The scene the light belongs to
  45047. */
  45048. function HemisphericLight(name, direction, scene) {
  45049. var _this = _super.call(this, name, scene) || this;
  45050. /**
  45051. * The groundColor is the light in the opposite direction to the one specified during creation.
  45052. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45053. */
  45054. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45055. _this.direction = direction || BABYLON.Vector3.Up();
  45056. return _this;
  45057. }
  45058. HemisphericLight.prototype._buildUniformLayout = function () {
  45059. this._uniformBuffer.addUniform("vLightData", 4);
  45060. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45061. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45062. this._uniformBuffer.addUniform("vLightGround", 3);
  45063. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45064. this._uniformBuffer.addUniform("depthValues", 2);
  45065. this._uniformBuffer.create();
  45066. };
  45067. /**
  45068. * Returns the string "HemisphericLight".
  45069. * @return The class name
  45070. */
  45071. HemisphericLight.prototype.getClassName = function () {
  45072. return "HemisphericLight";
  45073. };
  45074. /**
  45075. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45076. * Returns the updated direction.
  45077. * @param target The target the direction should point to
  45078. * @return The computed direction
  45079. */
  45080. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45081. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45082. return this.direction;
  45083. };
  45084. /**
  45085. * Returns the shadow generator associated to the light.
  45086. * @returns Always null for hemispheric lights because it does not support shadows.
  45087. */
  45088. HemisphericLight.prototype.getShadowGenerator = function () {
  45089. return null;
  45090. };
  45091. /**
  45092. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45093. * @param effect The effect to update
  45094. * @param lightIndex The index of the light in the effect to update
  45095. * @returns The hemispheric light
  45096. */
  45097. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45098. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45099. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45100. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45101. return this;
  45102. };
  45103. /**
  45104. * @ignore internal use only.
  45105. */
  45106. HemisphericLight.prototype._getWorldMatrix = function () {
  45107. if (!this._worldMatrix) {
  45108. this._worldMatrix = BABYLON.Matrix.Identity();
  45109. }
  45110. return this._worldMatrix;
  45111. };
  45112. /**
  45113. * Returns the integer 3.
  45114. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45115. */
  45116. HemisphericLight.prototype.getTypeID = function () {
  45117. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45118. };
  45119. __decorate([
  45120. BABYLON.serializeAsColor3()
  45121. ], HemisphericLight.prototype, "groundColor", void 0);
  45122. __decorate([
  45123. BABYLON.serializeAsVector3()
  45124. ], HemisphericLight.prototype, "direction", void 0);
  45125. return HemisphericLight;
  45126. }(BABYLON.Light));
  45127. BABYLON.HemisphericLight = HemisphericLight;
  45128. })(BABYLON || (BABYLON = {}));
  45129. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45130. var BABYLON;
  45131. (function (BABYLON) {
  45132. /**
  45133. * Base implementation of @see IShadowLight
  45134. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45135. */
  45136. var ShadowLight = /** @class */ (function (_super) {
  45137. __extends(ShadowLight, _super);
  45138. function ShadowLight() {
  45139. var _this = _super !== null && _super.apply(this, arguments) || this;
  45140. _this._needProjectionMatrixCompute = true;
  45141. return _this;
  45142. }
  45143. ShadowLight.prototype._setPosition = function (value) {
  45144. this._position = value;
  45145. };
  45146. Object.defineProperty(ShadowLight.prototype, "position", {
  45147. /**
  45148. * Sets the position the shadow will be casted from. Also use as the light position for both
  45149. * point and spot lights.
  45150. */
  45151. get: function () {
  45152. return this._position;
  45153. },
  45154. /**
  45155. * Sets the position the shadow will be casted from. Also use as the light position for both
  45156. * point and spot lights.
  45157. */
  45158. set: function (value) {
  45159. this._setPosition(value);
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. ShadowLight.prototype._setDirection = function (value) {
  45165. this._direction = value;
  45166. };
  45167. Object.defineProperty(ShadowLight.prototype, "direction", {
  45168. /**
  45169. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45170. * Also use as the light direction on spot and directional lights.
  45171. */
  45172. get: function () {
  45173. return this._direction;
  45174. },
  45175. /**
  45176. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45177. * Also use as the light direction on spot and directional lights.
  45178. */
  45179. set: function (value) {
  45180. this._setDirection(value);
  45181. },
  45182. enumerable: true,
  45183. configurable: true
  45184. });
  45185. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45186. /**
  45187. * Gets the shadow projection clipping minimum z value.
  45188. */
  45189. get: function () {
  45190. return this._shadowMinZ;
  45191. },
  45192. /**
  45193. * Sets the shadow projection clipping minimum z value.
  45194. */
  45195. set: function (value) {
  45196. this._shadowMinZ = value;
  45197. this.forceProjectionMatrixCompute();
  45198. },
  45199. enumerable: true,
  45200. configurable: true
  45201. });
  45202. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45203. /**
  45204. * Sets the shadow projection clipping maximum z value.
  45205. */
  45206. get: function () {
  45207. return this._shadowMaxZ;
  45208. },
  45209. /**
  45210. * Gets the shadow projection clipping maximum z value.
  45211. */
  45212. set: function (value) {
  45213. this._shadowMaxZ = value;
  45214. this.forceProjectionMatrixCompute();
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. /**
  45220. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45221. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45222. */
  45223. ShadowLight.prototype.computeTransformedInformation = function () {
  45224. if (this.parent && this.parent.getWorldMatrix) {
  45225. if (!this.transformedPosition) {
  45226. this.transformedPosition = BABYLON.Vector3.Zero();
  45227. }
  45228. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45229. // In case the direction is present.
  45230. if (this.direction) {
  45231. if (!this.transformedDirection) {
  45232. this.transformedDirection = BABYLON.Vector3.Zero();
  45233. }
  45234. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45235. }
  45236. return true;
  45237. }
  45238. return false;
  45239. };
  45240. /**
  45241. * Return the depth scale used for the shadow map.
  45242. * @returns the depth scale.
  45243. */
  45244. ShadowLight.prototype.getDepthScale = function () {
  45245. return 50.0;
  45246. };
  45247. /**
  45248. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45249. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45250. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45251. */
  45252. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45253. return this.transformedDirection ? this.transformedDirection : this.direction;
  45254. };
  45255. /**
  45256. * Returns the ShadowLight absolute position in the World.
  45257. * @returns the position vector in world space
  45258. */
  45259. ShadowLight.prototype.getAbsolutePosition = function () {
  45260. return this.transformedPosition ? this.transformedPosition : this.position;
  45261. };
  45262. /**
  45263. * Sets the ShadowLight direction toward the passed target.
  45264. * @param target The point tot target in local space
  45265. * @returns the updated ShadowLight direction
  45266. */
  45267. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45268. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45269. return this.direction;
  45270. };
  45271. /**
  45272. * Returns the light rotation in euler definition.
  45273. * @returns the x y z rotation in local space.
  45274. */
  45275. ShadowLight.prototype.getRotation = function () {
  45276. this.direction.normalize();
  45277. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45278. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45279. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45280. };
  45281. /**
  45282. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45283. * @returns true if a cube texture needs to be use
  45284. */
  45285. ShadowLight.prototype.needCube = function () {
  45286. return false;
  45287. };
  45288. /**
  45289. * Detects if the projection matrix requires to be recomputed this frame.
  45290. * @returns true if it requires to be recomputed otherwise, false.
  45291. */
  45292. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45293. return this._needProjectionMatrixCompute;
  45294. };
  45295. /**
  45296. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45297. */
  45298. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45299. this._needProjectionMatrixCompute = true;
  45300. };
  45301. /**
  45302. * Get the world matrix of the sahdow lights.
  45303. * @ignore Internal Use Only
  45304. */
  45305. ShadowLight.prototype._getWorldMatrix = function () {
  45306. if (!this._worldMatrix) {
  45307. this._worldMatrix = BABYLON.Matrix.Identity();
  45308. }
  45309. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45310. return this._worldMatrix;
  45311. };
  45312. /**
  45313. * Gets the minZ used for shadow according to both the scene and the light.
  45314. * @param activeCamera The camera we are returning the min for
  45315. * @returns the depth min z
  45316. */
  45317. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45318. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45319. };
  45320. /**
  45321. * Gets the maxZ used for shadow according to both the scene and the light.
  45322. * @param activeCamera The camera we are returning the max for
  45323. * @returns the depth max z
  45324. */
  45325. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45326. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45327. };
  45328. /**
  45329. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45330. * @param matrix The materix to updated with the projection information
  45331. * @param viewMatrix The transform matrix of the light
  45332. * @param renderList The list of mesh to render in the map
  45333. * @returns The current light
  45334. */
  45335. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45336. if (this.customProjectionMatrixBuilder) {
  45337. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45338. }
  45339. else {
  45340. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45341. }
  45342. return this;
  45343. };
  45344. __decorate([
  45345. BABYLON.serializeAsVector3()
  45346. ], ShadowLight.prototype, "position", null);
  45347. __decorate([
  45348. BABYLON.serializeAsVector3()
  45349. ], ShadowLight.prototype, "direction", null);
  45350. __decorate([
  45351. BABYLON.serialize()
  45352. ], ShadowLight.prototype, "shadowMinZ", null);
  45353. __decorate([
  45354. BABYLON.serialize()
  45355. ], ShadowLight.prototype, "shadowMaxZ", null);
  45356. return ShadowLight;
  45357. }(BABYLON.Light));
  45358. BABYLON.ShadowLight = ShadowLight;
  45359. })(BABYLON || (BABYLON = {}));
  45360. //# sourceMappingURL=babylon.shadowLight.js.map
  45361. var BABYLON;
  45362. (function (BABYLON) {
  45363. /**
  45364. * A point light is a light defined by an unique point in world space.
  45365. * The light is emitted in every direction from this point.
  45366. * A good example of a point light is a standard light bulb.
  45367. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45368. */
  45369. var PointLight = /** @class */ (function (_super) {
  45370. __extends(PointLight, _super);
  45371. /**
  45372. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45373. * A PointLight emits the light in every direction.
  45374. * It can cast shadows.
  45375. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45376. * ```javascript
  45377. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45378. * ```
  45379. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45380. * @param name The light friendly name
  45381. * @param position The position of the point light in the scene
  45382. * @param scene The scene the lights belongs to
  45383. */
  45384. function PointLight(name, position, scene) {
  45385. var _this = _super.call(this, name, scene) || this;
  45386. _this._shadowAngle = Math.PI / 2;
  45387. _this.position = position;
  45388. return _this;
  45389. }
  45390. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45391. /**
  45392. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45393. * This specifies what angle the shadow will use to be created.
  45394. *
  45395. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45396. */
  45397. get: function () {
  45398. return this._shadowAngle;
  45399. },
  45400. /**
  45401. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45402. * This specifies what angle the shadow will use to be created.
  45403. *
  45404. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45405. */
  45406. set: function (value) {
  45407. this._shadowAngle = value;
  45408. this.forceProjectionMatrixCompute();
  45409. },
  45410. enumerable: true,
  45411. configurable: true
  45412. });
  45413. Object.defineProperty(PointLight.prototype, "direction", {
  45414. /**
  45415. * Gets the direction if it has been set.
  45416. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45417. */
  45418. get: function () {
  45419. return this._direction;
  45420. },
  45421. /**
  45422. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45423. */
  45424. set: function (value) {
  45425. var previousNeedCube = this.needCube();
  45426. this._direction = value;
  45427. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45428. this._shadowGenerator.recreateShadowMap();
  45429. }
  45430. },
  45431. enumerable: true,
  45432. configurable: true
  45433. });
  45434. /**
  45435. * Returns the string "PointLight"
  45436. * @returns the class name
  45437. */
  45438. PointLight.prototype.getClassName = function () {
  45439. return "PointLight";
  45440. };
  45441. /**
  45442. * Returns the integer 0.
  45443. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45444. */
  45445. PointLight.prototype.getTypeID = function () {
  45446. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45447. };
  45448. /**
  45449. * Specifies wether or not the shadowmap should be a cube texture.
  45450. * @returns true if the shadowmap needs to be a cube texture.
  45451. */
  45452. PointLight.prototype.needCube = function () {
  45453. return !this.direction;
  45454. };
  45455. /**
  45456. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45457. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45458. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45459. */
  45460. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45461. if (this.direction) {
  45462. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45463. }
  45464. else {
  45465. switch (faceIndex) {
  45466. case 0:
  45467. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45468. case 1:
  45469. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45470. case 2:
  45471. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45472. case 3:
  45473. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45474. case 4:
  45475. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45476. case 5:
  45477. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45478. }
  45479. }
  45480. return BABYLON.Vector3.Zero();
  45481. };
  45482. /**
  45483. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45484. * - fov = PI / 2
  45485. * - aspect ratio : 1.0
  45486. * - z-near and far equal to the active camera minZ and maxZ.
  45487. * Returns the PointLight.
  45488. */
  45489. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45490. var activeCamera = this.getScene().activeCamera;
  45491. if (!activeCamera) {
  45492. return;
  45493. }
  45494. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45495. };
  45496. PointLight.prototype._buildUniformLayout = function () {
  45497. this._uniformBuffer.addUniform("vLightData", 4);
  45498. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45499. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45500. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45501. this._uniformBuffer.addUniform("depthValues", 2);
  45502. this._uniformBuffer.create();
  45503. };
  45504. /**
  45505. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45506. * @param effect The effect to update
  45507. * @param lightIndex The index of the light in the effect to update
  45508. * @returns The point light
  45509. */
  45510. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45511. if (this.computeTransformedInformation()) {
  45512. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45513. return this;
  45514. }
  45515. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45516. return this;
  45517. };
  45518. __decorate([
  45519. BABYLON.serialize()
  45520. ], PointLight.prototype, "shadowAngle", null);
  45521. return PointLight;
  45522. }(BABYLON.ShadowLight));
  45523. BABYLON.PointLight = PointLight;
  45524. })(BABYLON || (BABYLON = {}));
  45525. //# sourceMappingURL=babylon.pointLight.js.map
  45526. var BABYLON;
  45527. (function (BABYLON) {
  45528. /**
  45529. * A directional light is defined by a direction (what a surprise!).
  45530. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45531. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  45532. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45533. */
  45534. var DirectionalLight = /** @class */ (function (_super) {
  45535. __extends(DirectionalLight, _super);
  45536. /**
  45537. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45538. * The directional light is emitted from everywhere in the given direction.
  45539. * It can cast shawdows.
  45540. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45541. * @param name The friendly name of the light
  45542. * @param direction The direction of the light
  45543. * @param scene The scene the light belongs to
  45544. */
  45545. function DirectionalLight(name, direction, scene) {
  45546. var _this = _super.call(this, name, scene) || this;
  45547. _this._shadowFrustumSize = 0;
  45548. _this._shadowOrthoScale = 0.5;
  45549. /**
  45550. * Automatically compute the projection matrix to best fit (including all the casters)
  45551. * on each frame.
  45552. */
  45553. _this.autoUpdateExtends = true;
  45554. // Cache
  45555. _this._orthoLeft = Number.MAX_VALUE;
  45556. _this._orthoRight = Number.MIN_VALUE;
  45557. _this._orthoTop = Number.MIN_VALUE;
  45558. _this._orthoBottom = Number.MAX_VALUE;
  45559. _this.position = direction.scale(-1.0);
  45560. _this.direction = direction;
  45561. return _this;
  45562. }
  45563. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45564. /**
  45565. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45566. */
  45567. get: function () {
  45568. return this._shadowFrustumSize;
  45569. },
  45570. /**
  45571. * Specifies a fix frustum size for the shadow generation.
  45572. */
  45573. set: function (value) {
  45574. this._shadowFrustumSize = value;
  45575. this.forceProjectionMatrixCompute();
  45576. },
  45577. enumerable: true,
  45578. configurable: true
  45579. });
  45580. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45581. /**
  45582. * Gets the shadow projection scale against the optimal computed one.
  45583. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45584. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45585. */
  45586. get: function () {
  45587. return this._shadowOrthoScale;
  45588. },
  45589. /**
  45590. * Sets the shadow projection scale against the optimal computed one.
  45591. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45592. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45593. */
  45594. set: function (value) {
  45595. this._shadowOrthoScale = value;
  45596. this.forceProjectionMatrixCompute();
  45597. },
  45598. enumerable: true,
  45599. configurable: true
  45600. });
  45601. /**
  45602. * Returns the string "DirectionalLight".
  45603. * @return The class name
  45604. */
  45605. DirectionalLight.prototype.getClassName = function () {
  45606. return "DirectionalLight";
  45607. };
  45608. /**
  45609. * Returns the integer 1.
  45610. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45611. */
  45612. DirectionalLight.prototype.getTypeID = function () {
  45613. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45614. };
  45615. /**
  45616. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45617. * Returns the DirectionalLight Shadow projection matrix.
  45618. */
  45619. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45620. if (this.shadowFrustumSize > 0) {
  45621. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45622. }
  45623. else {
  45624. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45625. }
  45626. };
  45627. /**
  45628. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45629. * Returns the DirectionalLight Shadow projection matrix.
  45630. */
  45631. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45632. var activeCamera = this.getScene().activeCamera;
  45633. if (!activeCamera) {
  45634. return;
  45635. }
  45636. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45637. };
  45638. /**
  45639. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45640. * Returns the DirectionalLight Shadow projection matrix.
  45641. */
  45642. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45643. var activeCamera = this.getScene().activeCamera;
  45644. if (!activeCamera) {
  45645. return;
  45646. }
  45647. // Check extends
  45648. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45649. var tempVector3 = BABYLON.Vector3.Zero();
  45650. this._orthoLeft = Number.MAX_VALUE;
  45651. this._orthoRight = Number.MIN_VALUE;
  45652. this._orthoTop = Number.MIN_VALUE;
  45653. this._orthoBottom = Number.MAX_VALUE;
  45654. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45655. var mesh = renderList[meshIndex];
  45656. if (!mesh) {
  45657. continue;
  45658. }
  45659. var boundingInfo = mesh.getBoundingInfo();
  45660. var boundingBox = boundingInfo.boundingBox;
  45661. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45662. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45663. if (tempVector3.x < this._orthoLeft)
  45664. this._orthoLeft = tempVector3.x;
  45665. if (tempVector3.y < this._orthoBottom)
  45666. this._orthoBottom = tempVector3.y;
  45667. if (tempVector3.x > this._orthoRight)
  45668. this._orthoRight = tempVector3.x;
  45669. if (tempVector3.y > this._orthoTop)
  45670. this._orthoTop = tempVector3.y;
  45671. }
  45672. }
  45673. }
  45674. var xOffset = this._orthoRight - this._orthoLeft;
  45675. var yOffset = this._orthoTop - this._orthoBottom;
  45676. 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);
  45677. };
  45678. DirectionalLight.prototype._buildUniformLayout = function () {
  45679. this._uniformBuffer.addUniform("vLightData", 4);
  45680. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45681. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45682. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45683. this._uniformBuffer.addUniform("depthValues", 2);
  45684. this._uniformBuffer.create();
  45685. };
  45686. /**
  45687. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45688. * @param effect The effect to update
  45689. * @param lightIndex The index of the light in the effect to update
  45690. * @returns The directional light
  45691. */
  45692. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45693. if (this.computeTransformedInformation()) {
  45694. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45695. return this;
  45696. }
  45697. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45698. return this;
  45699. };
  45700. /**
  45701. * Gets the minZ used for shadow according to both the scene and the light.
  45702. *
  45703. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45704. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45705. * @param activeCamera The camera we are returning the min for
  45706. * @returns the depth min z
  45707. */
  45708. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45709. return 1;
  45710. };
  45711. /**
  45712. * Gets the maxZ used for shadow according to both the scene and the light.
  45713. *
  45714. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45715. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45716. * @param activeCamera The camera we are returning the max for
  45717. * @returns the depth max z
  45718. */
  45719. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45720. return 1;
  45721. };
  45722. __decorate([
  45723. BABYLON.serialize()
  45724. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45725. __decorate([
  45726. BABYLON.serialize()
  45727. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45731. return DirectionalLight;
  45732. }(BABYLON.ShadowLight));
  45733. BABYLON.DirectionalLight = DirectionalLight;
  45734. })(BABYLON || (BABYLON = {}));
  45735. //# sourceMappingURL=babylon.directionalLight.js.map
  45736. var BABYLON;
  45737. (function (BABYLON) {
  45738. /**
  45739. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45740. * These values define a cone of light starting from the position, emitting toward the direction.
  45741. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45742. * and the exponent defines the speed of the decay of the light with distance (reach).
  45743. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45744. */
  45745. var SpotLight = /** @class */ (function (_super) {
  45746. __extends(SpotLight, _super);
  45747. /**
  45748. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45749. * It can cast shadows.
  45750. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45751. * @param name The light friendly name
  45752. * @param position The position of the spot light in the scene
  45753. * @param direction The direction of the light in the scene
  45754. * @param angle The cone angle of the light in Radians
  45755. * @param exponent The light decay speed with the distance from the emission spot
  45756. * @param scene The scene the lights belongs to
  45757. */
  45758. function SpotLight(name, position, direction, angle, exponent, scene) {
  45759. var _this = _super.call(this, name, scene) || this;
  45760. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45761. _this._projectionTextureLightNear = 1e-6;
  45762. _this._projectionTextureLightFar = 1000.0;
  45763. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45764. _this._projectionTextureViewLightDirty = true;
  45765. _this._projectionTextureProjectionLightDirty = true;
  45766. _this._projectionTextureDirty = true;
  45767. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45768. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45769. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45770. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45771. _this.position = position;
  45772. _this.direction = direction;
  45773. _this.angle = angle;
  45774. _this.exponent = exponent;
  45775. return _this;
  45776. }
  45777. Object.defineProperty(SpotLight.prototype, "angle", {
  45778. /**
  45779. * Gets the cone angle of the spot light in Radians.
  45780. */
  45781. get: function () {
  45782. return this._angle;
  45783. },
  45784. /**
  45785. * Sets the cone angle of the spot light in Radians.
  45786. */
  45787. set: function (value) {
  45788. this._angle = value;
  45789. this._projectionTextureProjectionLightDirty = true;
  45790. this.forceProjectionMatrixCompute();
  45791. },
  45792. enumerable: true,
  45793. configurable: true
  45794. });
  45795. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45796. /**
  45797. * Allows scaling the angle of the light for shadow generation only.
  45798. */
  45799. get: function () {
  45800. return this._shadowAngleScale;
  45801. },
  45802. /**
  45803. * Allows scaling the angle of the light for shadow generation only.
  45804. */
  45805. set: function (value) {
  45806. this._shadowAngleScale = value;
  45807. this.forceProjectionMatrixCompute();
  45808. },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45813. /**
  45814. * Allows reading the projecton texture
  45815. */
  45816. get: function () {
  45817. return this._projectionTextureMatrix;
  45818. },
  45819. enumerable: true,
  45820. configurable: true
  45821. });
  45822. ;
  45823. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45824. /**
  45825. * Gets the near clip of the Spotlight for texture projection.
  45826. */
  45827. get: function () {
  45828. return this._projectionTextureLightNear;
  45829. },
  45830. /**
  45831. * Sets the near clip of the Spotlight for texture projection.
  45832. */
  45833. set: function (value) {
  45834. this._projectionTextureLightNear = value;
  45835. this._projectionTextureProjectionLightDirty = true;
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45841. /**
  45842. * Gets the far clip of the Spotlight for texture projection.
  45843. */
  45844. get: function () {
  45845. return this._projectionTextureLightFar;
  45846. },
  45847. /**
  45848. * Sets the far clip of the Spotlight for texture projection.
  45849. */
  45850. set: function (value) {
  45851. this._projectionTextureLightFar = value;
  45852. this._projectionTextureProjectionLightDirty = true;
  45853. },
  45854. enumerable: true,
  45855. configurable: true
  45856. });
  45857. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45858. /**
  45859. * Gets the Up vector of the Spotlight for texture projection.
  45860. */
  45861. get: function () {
  45862. return this._projectionTextureUpDirection;
  45863. },
  45864. /**
  45865. * Sets the Up vector of the Spotlight for texture projection.
  45866. */
  45867. set: function (value) {
  45868. this._projectionTextureUpDirection = value;
  45869. this._projectionTextureProjectionLightDirty = true;
  45870. },
  45871. enumerable: true,
  45872. configurable: true
  45873. });
  45874. ;
  45875. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45876. /**
  45877. * Gets the projection texture of the light.
  45878. */
  45879. get: function () {
  45880. return this._projectionTexture;
  45881. },
  45882. /**
  45883. * Sets the projection texture of the light.
  45884. */
  45885. set: function (value) {
  45886. this._projectionTexture = value;
  45887. this._projectionTextureDirty = true;
  45888. },
  45889. enumerable: true,
  45890. configurable: true
  45891. });
  45892. /**
  45893. * Returns the string "SpotLight".
  45894. * @returns the class name
  45895. */
  45896. SpotLight.prototype.getClassName = function () {
  45897. return "SpotLight";
  45898. };
  45899. /**
  45900. * Returns the integer 2.
  45901. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45902. */
  45903. SpotLight.prototype.getTypeID = function () {
  45904. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45905. };
  45906. /**
  45907. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45908. */
  45909. SpotLight.prototype._setDirection = function (value) {
  45910. _super.prototype._setDirection.call(this, value);
  45911. this._projectionTextureViewLightDirty = true;
  45912. };
  45913. /**
  45914. * Overrides the position setter to recompute the projection texture view light Matrix.
  45915. */
  45916. SpotLight.prototype._setPosition = function (value) {
  45917. _super.prototype._setPosition.call(this, value);
  45918. this._projectionTextureViewLightDirty = true;
  45919. };
  45920. /**
  45921. * 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.
  45922. * Returns the SpotLight.
  45923. */
  45924. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45925. var activeCamera = this.getScene().activeCamera;
  45926. if (!activeCamera) {
  45927. return;
  45928. }
  45929. this._shadowAngleScale = this._shadowAngleScale || 1;
  45930. var angle = this._shadowAngleScale * this._angle;
  45931. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45932. };
  45933. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45934. this._projectionTextureViewLightDirty = false;
  45935. this._projectionTextureDirty = true;
  45936. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45937. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45938. };
  45939. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45940. this._projectionTextureProjectionLightDirty = false;
  45941. this._projectionTextureDirty = true;
  45942. var light_far = this.projectionTextureLightFar;
  45943. var light_near = this.projectionTextureLightNear;
  45944. var P = light_far / (light_far - light_near);
  45945. var Q = -P * light_near;
  45946. var S = 1.0 / Math.tan(this._angle / 2.0);
  45947. var A = 1.0;
  45948. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45949. };
  45950. /**
  45951. * Main function for light texture projection matrix computing.
  45952. */
  45953. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45954. this._projectionTextureDirty = false;
  45955. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45956. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45957. };
  45958. SpotLight.prototype._buildUniformLayout = function () {
  45959. this._uniformBuffer.addUniform("vLightData", 4);
  45960. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45961. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45962. this._uniformBuffer.addUniform("vLightDirection", 3);
  45963. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45964. this._uniformBuffer.addUniform("depthValues", 2);
  45965. this._uniformBuffer.create();
  45966. };
  45967. /**
  45968. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45969. * @param effect The effect to update
  45970. * @param lightIndex The index of the light in the effect to update
  45971. * @returns The spot light
  45972. */
  45973. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45974. var normalizeDirection;
  45975. if (this.computeTransformedInformation()) {
  45976. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45977. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45978. }
  45979. else {
  45980. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45981. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45982. }
  45983. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45984. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45985. if (this._projectionTextureViewLightDirty) {
  45986. this._computeProjectionTextureViewLightMatrix();
  45987. }
  45988. if (this._projectionTextureProjectionLightDirty) {
  45989. this._computeProjectionTextureProjectionLightMatrix();
  45990. }
  45991. if (this._projectionTextureDirty) {
  45992. this._computeProjectionTextureMatrix();
  45993. }
  45994. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45995. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45996. }
  45997. return this;
  45998. };
  45999. /**
  46000. * Disposes the light and the associated resources.
  46001. */
  46002. SpotLight.prototype.dispose = function () {
  46003. _super.prototype.dispose.call(this);
  46004. if (this._projectionTexture) {
  46005. this._projectionTexture.dispose();
  46006. }
  46007. };
  46008. __decorate([
  46009. BABYLON.serialize()
  46010. ], SpotLight.prototype, "angle", null);
  46011. __decorate([
  46012. BABYLON.serialize()
  46013. ], SpotLight.prototype, "shadowAngleScale", null);
  46014. __decorate([
  46015. BABYLON.serialize()
  46016. ], SpotLight.prototype, "exponent", void 0);
  46017. __decorate([
  46018. BABYLON.serialize()
  46019. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46020. __decorate([
  46021. BABYLON.serialize()
  46022. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46023. __decorate([
  46024. BABYLON.serialize()
  46025. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46026. __decorate([
  46027. BABYLON.serializeAsTexture("projectedLightTexture")
  46028. ], SpotLight.prototype, "_projectionTexture", void 0);
  46029. return SpotLight;
  46030. }(BABYLON.ShadowLight));
  46031. BABYLON.SpotLight = SpotLight;
  46032. })(BABYLON || (BABYLON = {}));
  46033. //# sourceMappingURL=babylon.spotLight.js.map
  46034. var BABYLON;
  46035. (function (BABYLON) {
  46036. /**
  46037. * Class used to override all child animations of a given target
  46038. */
  46039. var AnimationPropertiesOverride = /** @class */ (function () {
  46040. function AnimationPropertiesOverride() {
  46041. /**
  46042. * Gets or sets a value indicating if animation blending must be used
  46043. */
  46044. this.enableBlending = false;
  46045. /**
  46046. * Gets or sets the blending speed to use when enableBlending is true
  46047. */
  46048. this.blendingSpeed = 0.01;
  46049. /**
  46050. * Gets or sets the default loop mode to use
  46051. */
  46052. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46053. }
  46054. return AnimationPropertiesOverride;
  46055. }());
  46056. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46057. })(BABYLON || (BABYLON = {}));
  46058. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46059. var BABYLON;
  46060. (function (BABYLON) {
  46061. var AnimationRange = /** @class */ (function () {
  46062. function AnimationRange(name, from, to) {
  46063. this.name = name;
  46064. this.from = from;
  46065. this.to = to;
  46066. }
  46067. AnimationRange.prototype.clone = function () {
  46068. return new AnimationRange(this.name, this.from, this.to);
  46069. };
  46070. return AnimationRange;
  46071. }());
  46072. BABYLON.AnimationRange = AnimationRange;
  46073. /**
  46074. * Composed of a frame, and an action function
  46075. */
  46076. var AnimationEvent = /** @class */ (function () {
  46077. function AnimationEvent(frame, action, onlyOnce) {
  46078. this.frame = frame;
  46079. this.action = action;
  46080. this.onlyOnce = onlyOnce;
  46081. this.isDone = false;
  46082. }
  46083. return AnimationEvent;
  46084. }());
  46085. BABYLON.AnimationEvent = AnimationEvent;
  46086. var PathCursor = /** @class */ (function () {
  46087. function PathCursor(path) {
  46088. this.path = path;
  46089. this._onchange = new Array();
  46090. this.value = 0;
  46091. this.animations = new Array();
  46092. }
  46093. PathCursor.prototype.getPoint = function () {
  46094. var point = this.path.getPointAtLengthPosition(this.value);
  46095. return new BABYLON.Vector3(point.x, 0, point.y);
  46096. };
  46097. PathCursor.prototype.moveAhead = function (step) {
  46098. if (step === void 0) { step = 0.002; }
  46099. this.move(step);
  46100. return this;
  46101. };
  46102. PathCursor.prototype.moveBack = function (step) {
  46103. if (step === void 0) { step = 0.002; }
  46104. this.move(-step);
  46105. return this;
  46106. };
  46107. PathCursor.prototype.move = function (step) {
  46108. if (Math.abs(step) > 1) {
  46109. throw "step size should be less than 1.";
  46110. }
  46111. this.value += step;
  46112. this.ensureLimits();
  46113. this.raiseOnChange();
  46114. return this;
  46115. };
  46116. PathCursor.prototype.ensureLimits = function () {
  46117. while (this.value > 1) {
  46118. this.value -= 1;
  46119. }
  46120. while (this.value < 0) {
  46121. this.value += 1;
  46122. }
  46123. return this;
  46124. };
  46125. // used by animation engine
  46126. PathCursor.prototype.raiseOnChange = function () {
  46127. var _this = this;
  46128. this._onchange.forEach(function (f) { return f(_this); });
  46129. return this;
  46130. };
  46131. PathCursor.prototype.onchange = function (f) {
  46132. this._onchange.push(f);
  46133. return this;
  46134. };
  46135. return PathCursor;
  46136. }());
  46137. BABYLON.PathCursor = PathCursor;
  46138. var AnimationKeyInterpolation;
  46139. (function (AnimationKeyInterpolation) {
  46140. /**
  46141. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46142. */
  46143. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46144. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46145. var Animation = /** @class */ (function () {
  46146. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46147. this.name = name;
  46148. this.targetProperty = targetProperty;
  46149. this.framePerSecond = framePerSecond;
  46150. this.dataType = dataType;
  46151. this.loopMode = loopMode;
  46152. this.enableBlending = enableBlending;
  46153. this._runtimeAnimations = new Array();
  46154. // The set of event that will be linked to this animation
  46155. this._events = new Array();
  46156. this.blendingSpeed = 0.01;
  46157. this._ranges = {};
  46158. this.targetPropertyPath = targetProperty.split(".");
  46159. this.dataType = dataType;
  46160. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46161. }
  46162. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46163. var dataType = undefined;
  46164. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46165. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46166. }
  46167. else if (from instanceof BABYLON.Quaternion) {
  46168. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46169. }
  46170. else if (from instanceof BABYLON.Vector3) {
  46171. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46172. }
  46173. else if (from instanceof BABYLON.Vector2) {
  46174. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46175. }
  46176. else if (from instanceof BABYLON.Color3) {
  46177. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46178. }
  46179. else if (from instanceof BABYLON.Size) {
  46180. dataType = Animation.ANIMATIONTYPE_SIZE;
  46181. }
  46182. if (dataType == undefined) {
  46183. return null;
  46184. }
  46185. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46186. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46187. animation.setKeys(keys);
  46188. if (easingFunction !== undefined) {
  46189. animation.setEasingFunction(easingFunction);
  46190. }
  46191. return animation;
  46192. };
  46193. /**
  46194. * Sets up an animation.
  46195. * @param property the property to animate
  46196. * @param animationType the animation type to apply
  46197. * @param easingFunction the easing function used in the animation
  46198. * @returns The created animation
  46199. */
  46200. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46201. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46202. animation.setEasingFunction(easingFunction);
  46203. return animation;
  46204. };
  46205. /**
  46206. * Create and start an animation on a node
  46207. * @param {string} name defines the name of the global animation that will be run on all nodes
  46208. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46209. * @param {string} targetProperty defines property to animate
  46210. * @param {number} framePerSecond defines the number of frame per second yo use
  46211. * @param {number} totalFrame defines the number of frames in total
  46212. * @param {any} from defines the initial value
  46213. * @param {any} to defines the final value
  46214. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46215. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46216. * @param onAnimationEnd defines the callback to call when animation end
  46217. * @returns the animatable created for this animation
  46218. */
  46219. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46220. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46221. if (!animation) {
  46222. return null;
  46223. }
  46224. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46225. };
  46226. /**
  46227. * Create and start an animation on a node and its descendants
  46228. * @param {string} name defines the name of the global animation that will be run on all nodes
  46229. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46230. * @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.
  46231. * @param {string} targetProperty defines property to animate
  46232. * @param {number} framePerSecond defines the number of frame per second yo use
  46233. * @param {number} totalFrame defines the number of frames in total
  46234. * @param {any} from defines the initial value
  46235. * @param {any} to defines the final value
  46236. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46237. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46238. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46239. * @returns the list of animatables created for all nodes
  46240. * @example https://www.babylonjs-playground.com/#MH0VLI
  46241. */
  46242. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46243. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46244. if (!animation) {
  46245. return null;
  46246. }
  46247. var scene = node.getScene();
  46248. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46249. };
  46250. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46251. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46252. if (!animation) {
  46253. return null;
  46254. }
  46255. node.animations.push(animation);
  46256. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46257. };
  46258. /**
  46259. * Transition property of the Camera to the target Value.
  46260. * @param property The property to transition
  46261. * @param targetValue The target Value of the property
  46262. * @param host The object where the property to animate belongs
  46263. * @param scene Scene used to run the animation
  46264. * @param frameRate Framerate (in frame/s) to use
  46265. * @param transition The transition type we want to use
  46266. * @param duration The duration of the animation, in milliseconds
  46267. * @param onAnimationEnd Call back trigger at the end of the animation.
  46268. */
  46269. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46270. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46271. if (duration <= 0) {
  46272. host[property] = targetValue;
  46273. if (onAnimationEnd) {
  46274. onAnimationEnd();
  46275. }
  46276. return null;
  46277. }
  46278. var endFrame = frameRate * (duration / 1000);
  46279. transition.setKeys([{
  46280. frame: 0,
  46281. value: host[property].clone ? host[property].clone() : host[property]
  46282. },
  46283. {
  46284. frame: endFrame,
  46285. value: targetValue
  46286. }]);
  46287. if (!host.animations) {
  46288. host.animations = [];
  46289. }
  46290. host.animations.push(transition);
  46291. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46292. animation.onAnimationEnd = onAnimationEnd;
  46293. return animation;
  46294. };
  46295. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46296. /**
  46297. * Return the array of runtime animations currently using this animation
  46298. */
  46299. get: function () {
  46300. return this._runtimeAnimations;
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46306. get: function () {
  46307. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46308. var runtimeAnimation = _a[_i];
  46309. if (!runtimeAnimation.isStopped) {
  46310. return true;
  46311. }
  46312. }
  46313. return false;
  46314. },
  46315. enumerable: true,
  46316. configurable: true
  46317. });
  46318. // Methods
  46319. /**
  46320. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46321. */
  46322. Animation.prototype.toString = function (fullDetails) {
  46323. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46324. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46325. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46326. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46327. if (fullDetails) {
  46328. ret += ", Ranges: {";
  46329. var first = true;
  46330. for (var name in this._ranges) {
  46331. if (first) {
  46332. ret += ", ";
  46333. first = false;
  46334. }
  46335. ret += name;
  46336. }
  46337. ret += "}";
  46338. }
  46339. return ret;
  46340. };
  46341. /**
  46342. * Add an event to this animation.
  46343. */
  46344. Animation.prototype.addEvent = function (event) {
  46345. this._events.push(event);
  46346. };
  46347. /**
  46348. * Remove all events found at the given frame
  46349. * @param frame
  46350. */
  46351. Animation.prototype.removeEvents = function (frame) {
  46352. for (var index = 0; index < this._events.length; index++) {
  46353. if (this._events[index].frame === frame) {
  46354. this._events.splice(index, 1);
  46355. index--;
  46356. }
  46357. }
  46358. };
  46359. Animation.prototype.getEvents = function () {
  46360. return this._events;
  46361. };
  46362. Animation.prototype.createRange = function (name, from, to) {
  46363. // check name not already in use; could happen for bones after serialized
  46364. if (!this._ranges[name]) {
  46365. this._ranges[name] = new AnimationRange(name, from, to);
  46366. }
  46367. };
  46368. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46369. if (deleteFrames === void 0) { deleteFrames = true; }
  46370. var range = this._ranges[name];
  46371. if (!range) {
  46372. return;
  46373. }
  46374. if (deleteFrames) {
  46375. var from = range.from;
  46376. var to = range.to;
  46377. // this loop MUST go high to low for multiple splices to work
  46378. for (var key = this._keys.length - 1; key >= 0; key--) {
  46379. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46380. this._keys.splice(key, 1);
  46381. }
  46382. }
  46383. }
  46384. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46385. };
  46386. Animation.prototype.getRange = function (name) {
  46387. return this._ranges[name];
  46388. };
  46389. Animation.prototype.getKeys = function () {
  46390. return this._keys;
  46391. };
  46392. Animation.prototype.getHighestFrame = function () {
  46393. var ret = 0;
  46394. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46395. if (ret < this._keys[key].frame) {
  46396. ret = this._keys[key].frame;
  46397. }
  46398. }
  46399. return ret;
  46400. };
  46401. Animation.prototype.getEasingFunction = function () {
  46402. return this._easingFunction;
  46403. };
  46404. Animation.prototype.setEasingFunction = function (easingFunction) {
  46405. this._easingFunction = easingFunction;
  46406. };
  46407. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46408. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46409. };
  46410. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46411. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46412. };
  46413. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46414. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46415. };
  46416. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46417. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46418. };
  46419. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46420. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46421. };
  46422. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46423. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46424. };
  46425. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46426. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46427. };
  46428. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46429. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46430. };
  46431. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46432. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46433. };
  46434. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46435. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46436. };
  46437. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46438. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46439. };
  46440. Animation.prototype.clone = function () {
  46441. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46442. clone.enableBlending = this.enableBlending;
  46443. clone.blendingSpeed = this.blendingSpeed;
  46444. if (this._keys) {
  46445. clone.setKeys(this._keys);
  46446. }
  46447. if (this._ranges) {
  46448. clone._ranges = {};
  46449. for (var name in this._ranges) {
  46450. var range = this._ranges[name];
  46451. if (!range) {
  46452. continue;
  46453. }
  46454. clone._ranges[name] = range.clone();
  46455. }
  46456. }
  46457. return clone;
  46458. };
  46459. Animation.prototype.setKeys = function (values) {
  46460. this._keys = values.slice(0);
  46461. };
  46462. Animation.prototype.serialize = function () {
  46463. var serializationObject = {};
  46464. serializationObject.name = this.name;
  46465. serializationObject.property = this.targetProperty;
  46466. serializationObject.framePerSecond = this.framePerSecond;
  46467. serializationObject.dataType = this.dataType;
  46468. serializationObject.loopBehavior = this.loopMode;
  46469. serializationObject.enableBlending = this.enableBlending;
  46470. serializationObject.blendingSpeed = this.blendingSpeed;
  46471. var dataType = this.dataType;
  46472. serializationObject.keys = [];
  46473. var keys = this.getKeys();
  46474. for (var index = 0; index < keys.length; index++) {
  46475. var animationKey = keys[index];
  46476. var key = {};
  46477. key.frame = animationKey.frame;
  46478. switch (dataType) {
  46479. case Animation.ANIMATIONTYPE_FLOAT:
  46480. key.values = [animationKey.value];
  46481. break;
  46482. case Animation.ANIMATIONTYPE_QUATERNION:
  46483. case Animation.ANIMATIONTYPE_MATRIX:
  46484. case Animation.ANIMATIONTYPE_VECTOR3:
  46485. case Animation.ANIMATIONTYPE_COLOR3:
  46486. key.values = animationKey.value.asArray();
  46487. break;
  46488. }
  46489. serializationObject.keys.push(key);
  46490. }
  46491. serializationObject.ranges = [];
  46492. for (var name in this._ranges) {
  46493. var source = this._ranges[name];
  46494. if (!source) {
  46495. continue;
  46496. }
  46497. var range = {};
  46498. range.name = name;
  46499. range.from = source.from;
  46500. range.to = source.to;
  46501. serializationObject.ranges.push(range);
  46502. }
  46503. return serializationObject;
  46504. };
  46505. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46506. get: function () {
  46507. return Animation._ANIMATIONTYPE_FLOAT;
  46508. },
  46509. enumerable: true,
  46510. configurable: true
  46511. });
  46512. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46513. get: function () {
  46514. return Animation._ANIMATIONTYPE_VECTOR3;
  46515. },
  46516. enumerable: true,
  46517. configurable: true
  46518. });
  46519. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46520. get: function () {
  46521. return Animation._ANIMATIONTYPE_VECTOR2;
  46522. },
  46523. enumerable: true,
  46524. configurable: true
  46525. });
  46526. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46527. get: function () {
  46528. return Animation._ANIMATIONTYPE_SIZE;
  46529. },
  46530. enumerable: true,
  46531. configurable: true
  46532. });
  46533. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46534. get: function () {
  46535. return Animation._ANIMATIONTYPE_QUATERNION;
  46536. },
  46537. enumerable: true,
  46538. configurable: true
  46539. });
  46540. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46541. get: function () {
  46542. return Animation._ANIMATIONTYPE_MATRIX;
  46543. },
  46544. enumerable: true,
  46545. configurable: true
  46546. });
  46547. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46548. get: function () {
  46549. return Animation._ANIMATIONTYPE_COLOR3;
  46550. },
  46551. enumerable: true,
  46552. configurable: true
  46553. });
  46554. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46555. get: function () {
  46556. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46557. },
  46558. enumerable: true,
  46559. configurable: true
  46560. });
  46561. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46562. get: function () {
  46563. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46564. },
  46565. enumerable: true,
  46566. configurable: true
  46567. });
  46568. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46569. get: function () {
  46570. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46571. },
  46572. enumerable: true,
  46573. configurable: true
  46574. });
  46575. Animation.Parse = function (parsedAnimation) {
  46576. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46577. var dataType = parsedAnimation.dataType;
  46578. var keys = [];
  46579. var data;
  46580. var index;
  46581. if (parsedAnimation.enableBlending) {
  46582. animation.enableBlending = parsedAnimation.enableBlending;
  46583. }
  46584. if (parsedAnimation.blendingSpeed) {
  46585. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46586. }
  46587. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46588. var key = parsedAnimation.keys[index];
  46589. var inTangent;
  46590. var outTangent;
  46591. switch (dataType) {
  46592. case Animation.ANIMATIONTYPE_FLOAT:
  46593. data = key.values[0];
  46594. if (key.values.length >= 1) {
  46595. inTangent = key.values[1];
  46596. }
  46597. if (key.values.length >= 2) {
  46598. outTangent = key.values[2];
  46599. }
  46600. break;
  46601. case Animation.ANIMATIONTYPE_QUATERNION:
  46602. data = BABYLON.Quaternion.FromArray(key.values);
  46603. if (key.values.length >= 8) {
  46604. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46605. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46606. inTangent = _inTangent;
  46607. }
  46608. }
  46609. if (key.values.length >= 12) {
  46610. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46611. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46612. outTangent = _outTangent;
  46613. }
  46614. }
  46615. break;
  46616. case Animation.ANIMATIONTYPE_MATRIX:
  46617. data = BABYLON.Matrix.FromArray(key.values);
  46618. break;
  46619. case Animation.ANIMATIONTYPE_COLOR3:
  46620. data = BABYLON.Color3.FromArray(key.values);
  46621. break;
  46622. case Animation.ANIMATIONTYPE_VECTOR3:
  46623. default:
  46624. data = BABYLON.Vector3.FromArray(key.values);
  46625. break;
  46626. }
  46627. var keyData = {};
  46628. keyData.frame = key.frame;
  46629. keyData.value = data;
  46630. if (inTangent != undefined) {
  46631. keyData.inTangent = inTangent;
  46632. }
  46633. if (outTangent != undefined) {
  46634. keyData.outTangent = outTangent;
  46635. }
  46636. keys.push(keyData);
  46637. }
  46638. animation.setKeys(keys);
  46639. if (parsedAnimation.ranges) {
  46640. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46641. data = parsedAnimation.ranges[index];
  46642. animation.createRange(data.name, data.from, data.to);
  46643. }
  46644. }
  46645. return animation;
  46646. };
  46647. Animation.AppendSerializedAnimations = function (source, destination) {
  46648. if (source.animations) {
  46649. destination.animations = [];
  46650. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46651. var animation = source.animations[animationIndex];
  46652. destination.animations.push(animation.serialize());
  46653. }
  46654. }
  46655. };
  46656. Animation.AllowMatricesInterpolation = false;
  46657. // Statics
  46658. Animation._ANIMATIONTYPE_FLOAT = 0;
  46659. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46660. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46661. Animation._ANIMATIONTYPE_MATRIX = 3;
  46662. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46663. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46664. Animation._ANIMATIONTYPE_SIZE = 6;
  46665. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46666. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46667. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46668. return Animation;
  46669. }());
  46670. BABYLON.Animation = Animation;
  46671. })(BABYLON || (BABYLON = {}));
  46672. //# sourceMappingURL=babylon.animation.js.map
  46673. var BABYLON;
  46674. (function (BABYLON) {
  46675. /**
  46676. * This class defines the direct association between an animation and a target
  46677. */
  46678. var TargetedAnimation = /** @class */ (function () {
  46679. function TargetedAnimation() {
  46680. }
  46681. return TargetedAnimation;
  46682. }());
  46683. BABYLON.TargetedAnimation = TargetedAnimation;
  46684. /**
  46685. * Use this class to create coordinated animations on multiple targets
  46686. */
  46687. var AnimationGroup = /** @class */ (function () {
  46688. function AnimationGroup(name, scene) {
  46689. if (scene === void 0) { scene = null; }
  46690. this.name = name;
  46691. this._targetedAnimations = new Array();
  46692. this._animatables = new Array();
  46693. this._from = Number.MAX_VALUE;
  46694. this._to = -Number.MAX_VALUE;
  46695. this._speedRatio = 1;
  46696. this.onAnimationEndObservable = new BABYLON.Observable();
  46697. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46698. this._scene.animationGroups.push(this);
  46699. }
  46700. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46701. /**
  46702. * Define if the animations are started
  46703. */
  46704. get: function () {
  46705. return this._isStarted;
  46706. },
  46707. enumerable: true,
  46708. configurable: true
  46709. });
  46710. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46711. /**
  46712. * Gets or sets the speed ratio to use for all animations
  46713. */
  46714. get: function () {
  46715. return this._speedRatio;
  46716. },
  46717. /**
  46718. * Gets or sets the speed ratio to use for all animations
  46719. */
  46720. set: function (value) {
  46721. if (this._speedRatio === value) {
  46722. return;
  46723. }
  46724. this._speedRatio = value;
  46725. for (var index = 0; index < this._animatables.length; index++) {
  46726. var animatable = this._animatables[index];
  46727. animatable.speedRatio = this._speedRatio;
  46728. }
  46729. },
  46730. enumerable: true,
  46731. configurable: true
  46732. });
  46733. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46734. /**
  46735. * Gets the targeted animations for this animation group
  46736. */
  46737. get: function () {
  46738. return this._targetedAnimations;
  46739. },
  46740. enumerable: true,
  46741. configurable: true
  46742. });
  46743. /**
  46744. * Add an animation (with its target) in the group
  46745. * @param animation defines the animation we want to add
  46746. * @param target defines the target of the animation
  46747. * @returns the {BABYLON.TargetedAnimation} object
  46748. */
  46749. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46750. var targetedAnimation = {
  46751. animation: animation,
  46752. target: target
  46753. };
  46754. var keys = animation.getKeys();
  46755. if (this._from > keys[0].frame) {
  46756. this._from = keys[0].frame;
  46757. }
  46758. if (this._to < keys[keys.length - 1].frame) {
  46759. this._to = keys[keys.length - 1].frame;
  46760. }
  46761. this._targetedAnimations.push(targetedAnimation);
  46762. return targetedAnimation;
  46763. };
  46764. /**
  46765. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46766. * It can add constant keys at begin or end
  46767. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46768. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46769. */
  46770. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46771. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46772. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46773. beginFrame = Math.max(beginFrame, this._from);
  46774. endFrame = Math.min(endFrame, this._to);
  46775. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46776. var targetedAnimation = this._targetedAnimations[index];
  46777. var keys = targetedAnimation.animation.getKeys();
  46778. var startKey = keys[0];
  46779. var endKey = keys[keys.length - 1];
  46780. if (startKey.frame > beginFrame) {
  46781. var newKey = {
  46782. frame: beginFrame,
  46783. value: startKey.value,
  46784. inTangent: startKey.inTangent,
  46785. outTangent: startKey.outTangent,
  46786. interpolation: startKey.interpolation
  46787. };
  46788. keys.splice(0, 0, newKey);
  46789. }
  46790. if (endKey.frame < endFrame) {
  46791. var newKey = {
  46792. frame: endFrame,
  46793. value: endKey.value,
  46794. inTangent: endKey.outTangent,
  46795. outTangent: endKey.outTangent,
  46796. interpolation: endKey.interpolation
  46797. };
  46798. keys.push(newKey);
  46799. }
  46800. }
  46801. return this;
  46802. };
  46803. /**
  46804. * Start all animations on given targets
  46805. * @param loop defines if animations must loop
  46806. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46807. */
  46808. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46809. var _this = this;
  46810. if (loop === void 0) { loop = false; }
  46811. if (speedRatio === void 0) { speedRatio = 1; }
  46812. if (this._isStarted || this._targetedAnimations.length === 0) {
  46813. return this;
  46814. }
  46815. var _loop_1 = function () {
  46816. var targetedAnimation = this_1._targetedAnimations[index];
  46817. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46818. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46819. }));
  46820. };
  46821. var this_1 = this;
  46822. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46823. _loop_1();
  46824. }
  46825. this._speedRatio = speedRatio;
  46826. this._isStarted = true;
  46827. return this;
  46828. };
  46829. /**
  46830. * Pause all animations
  46831. */
  46832. AnimationGroup.prototype.pause = function () {
  46833. if (!this._isStarted) {
  46834. return this;
  46835. }
  46836. for (var index = 0; index < this._animatables.length; index++) {
  46837. var animatable = this._animatables[index];
  46838. animatable.pause();
  46839. }
  46840. return this;
  46841. };
  46842. /**
  46843. * Play all animations to initial state
  46844. * This function will start() the animations if they were not started or will restart() them if they were paused
  46845. * @param loop defines if animations must loop
  46846. */
  46847. AnimationGroup.prototype.play = function (loop) {
  46848. if (this.isStarted) {
  46849. if (loop !== undefined) {
  46850. for (var index = 0; index < this._animatables.length; index++) {
  46851. var animatable = this._animatables[index];
  46852. animatable.loopAnimation = loop;
  46853. }
  46854. }
  46855. this.restart();
  46856. }
  46857. else {
  46858. this.start(loop, this._speedRatio);
  46859. }
  46860. return this;
  46861. };
  46862. /**
  46863. * Reset all animations to initial state
  46864. */
  46865. AnimationGroup.prototype.reset = function () {
  46866. if (!this._isStarted) {
  46867. return this;
  46868. }
  46869. for (var index = 0; index < this._animatables.length; index++) {
  46870. var animatable = this._animatables[index];
  46871. animatable.reset();
  46872. }
  46873. return this;
  46874. };
  46875. /**
  46876. * Restart animations from key 0
  46877. */
  46878. AnimationGroup.prototype.restart = function () {
  46879. if (!this._isStarted) {
  46880. return this;
  46881. }
  46882. for (var index = 0; index < this._animatables.length; index++) {
  46883. var animatable = this._animatables[index];
  46884. animatable.restart();
  46885. }
  46886. return this;
  46887. };
  46888. /**
  46889. * Stop all animations
  46890. */
  46891. AnimationGroup.prototype.stop = function () {
  46892. if (!this._isStarted) {
  46893. return this;
  46894. }
  46895. for (var index = 0; index < this._animatables.length; index++) {
  46896. var animatable = this._animatables[index];
  46897. animatable.stop();
  46898. }
  46899. this._isStarted = false;
  46900. return this;
  46901. };
  46902. /**
  46903. * Dispose all associated resources
  46904. */
  46905. AnimationGroup.prototype.dispose = function () {
  46906. this._targetedAnimations = [];
  46907. this._animatables = [];
  46908. var index = this._scene.animationGroups.indexOf(this);
  46909. if (index > -1) {
  46910. this._scene.animationGroups.splice(index, 1);
  46911. }
  46912. };
  46913. return AnimationGroup;
  46914. }());
  46915. BABYLON.AnimationGroup = AnimationGroup;
  46916. })(BABYLON || (BABYLON = {}));
  46917. //# sourceMappingURL=babylon.animationGroup.js.map
  46918. var BABYLON;
  46919. (function (BABYLON) {
  46920. var RuntimeAnimation = /** @class */ (function () {
  46921. function RuntimeAnimation(target, animation) {
  46922. this._offsetsCache = {};
  46923. this._highLimitsCache = {};
  46924. this._stopped = false;
  46925. this._blendingFactor = 0;
  46926. this._ratioOffset = 0;
  46927. this._animation = animation;
  46928. this._target = target;
  46929. animation._runtimeAnimations.push(this);
  46930. }
  46931. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46932. get: function () {
  46933. return this._animation;
  46934. },
  46935. enumerable: true,
  46936. configurable: true
  46937. });
  46938. RuntimeAnimation.prototype.reset = function () {
  46939. this._offsetsCache = {};
  46940. this._highLimitsCache = {};
  46941. this.currentFrame = 0;
  46942. this._blendingFactor = 0;
  46943. this._originalBlendValue = null;
  46944. };
  46945. RuntimeAnimation.prototype.isStopped = function () {
  46946. return this._stopped;
  46947. };
  46948. RuntimeAnimation.prototype.dispose = function () {
  46949. var index = this._animation.runtimeAnimations.indexOf(this);
  46950. if (index > -1) {
  46951. this._animation.runtimeAnimations.splice(index, 1);
  46952. }
  46953. };
  46954. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46955. if (typeof value === "function") {
  46956. return value();
  46957. }
  46958. return value;
  46959. };
  46960. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46961. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46962. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46963. }
  46964. this.currentFrame = currentFrame;
  46965. var keys = this._animation.getKeys();
  46966. // Try to get a hash to find the right key
  46967. 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));
  46968. if (keys[startKeyIndex].frame >= currentFrame) {
  46969. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46970. startKeyIndex--;
  46971. }
  46972. }
  46973. for (var key = startKeyIndex; key < keys.length; key++) {
  46974. var endKey = keys[key + 1];
  46975. if (endKey.frame >= currentFrame) {
  46976. var startKey = keys[key];
  46977. var startValue = this._getKeyValue(startKey.value);
  46978. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46979. return startValue;
  46980. }
  46981. var endValue = this._getKeyValue(endKey.value);
  46982. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46983. var frameDelta = endKey.frame - startKey.frame;
  46984. // gradient : percent of currentFrame between the frame inf and the frame sup
  46985. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46986. // check for easingFunction and correction of gradient
  46987. var easingFunction = this._animation.getEasingFunction();
  46988. if (easingFunction != null) {
  46989. gradient = easingFunction.ease(gradient);
  46990. }
  46991. switch (this._animation.dataType) {
  46992. // Float
  46993. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46994. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46995. switch (loopMode) {
  46996. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46997. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46998. return floatValue;
  46999. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47000. return offsetValue * repeatCount + floatValue;
  47001. }
  47002. break;
  47003. // Quaternion
  47004. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47005. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47006. switch (loopMode) {
  47007. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47008. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47009. return quatValue;
  47010. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47011. return quatValue.add(offsetValue.scale(repeatCount));
  47012. }
  47013. return quatValue;
  47014. // Vector3
  47015. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47016. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47017. switch (loopMode) {
  47018. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47019. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47020. return vec3Value;
  47021. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47022. return vec3Value.add(offsetValue.scale(repeatCount));
  47023. }
  47024. // Vector2
  47025. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47026. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47027. switch (loopMode) {
  47028. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47029. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47030. return vec2Value;
  47031. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47032. return vec2Value.add(offsetValue.scale(repeatCount));
  47033. }
  47034. // Size
  47035. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47036. switch (loopMode) {
  47037. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47038. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47039. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47040. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47041. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47042. }
  47043. // Color3
  47044. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47045. switch (loopMode) {
  47046. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47047. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47048. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47049. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47050. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47051. }
  47052. // Matrix
  47053. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47054. switch (loopMode) {
  47055. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47056. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47057. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47058. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47059. }
  47060. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47061. return startValue;
  47062. }
  47063. default:
  47064. break;
  47065. }
  47066. break;
  47067. }
  47068. }
  47069. return this._getKeyValue(keys[keys.length - 1].value);
  47070. };
  47071. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47072. if (blend === void 0) { blend = false; }
  47073. // Set value
  47074. var path;
  47075. var destination;
  47076. var targetPropertyPath = this._animation.targetPropertyPath;
  47077. if (targetPropertyPath.length > 1) {
  47078. var property = this._target[targetPropertyPath[0]];
  47079. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47080. property = property[targetPropertyPath[index]];
  47081. }
  47082. path = targetPropertyPath[targetPropertyPath.length - 1];
  47083. destination = property;
  47084. }
  47085. else {
  47086. path = targetPropertyPath[0];
  47087. destination = this._target;
  47088. }
  47089. // Blending
  47090. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47091. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47092. if (enableBlending && this._blendingFactor <= 1.0) {
  47093. if (!this._originalBlendValue) {
  47094. if (destination[path].clone) {
  47095. this._originalBlendValue = destination[path].clone();
  47096. }
  47097. else {
  47098. this._originalBlendValue = destination[path];
  47099. }
  47100. }
  47101. if (this._originalBlendValue.prototype) {
  47102. if (this._originalBlendValue.prototype.Lerp) {
  47103. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47104. }
  47105. else {
  47106. destination[path] = currentValue;
  47107. }
  47108. }
  47109. else if (this._originalBlendValue.m) {
  47110. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47111. }
  47112. else {
  47113. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47114. }
  47115. this._blendingFactor += blendingSpeed;
  47116. }
  47117. else {
  47118. destination[path] = currentValue;
  47119. }
  47120. if (this._target.markAsDirty) {
  47121. this._target.markAsDirty(this._animation.targetProperty);
  47122. }
  47123. };
  47124. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47125. if (this._target && this._target.animationPropertiesOverride) {
  47126. return this._target.animationPropertiesOverride.loopMode;
  47127. }
  47128. return this._animation.loopMode;
  47129. };
  47130. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47131. var keys = this._animation.getKeys();
  47132. if (frame < keys[0].frame) {
  47133. frame = keys[0].frame;
  47134. }
  47135. else if (frame > keys[keys.length - 1].frame) {
  47136. frame = keys[keys.length - 1].frame;
  47137. }
  47138. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47139. this.setValue(currentValue);
  47140. };
  47141. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47142. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47143. this._ratioOffset = this._previousRatio - newRatio;
  47144. };
  47145. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47146. if (blend === void 0) { blend = false; }
  47147. var targetPropertyPath = this._animation.targetPropertyPath;
  47148. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47149. this._stopped = true;
  47150. return false;
  47151. }
  47152. var returnValue = true;
  47153. var keys = this._animation.getKeys();
  47154. // Adding a start key at frame 0 if missing
  47155. if (keys[0].frame !== 0) {
  47156. var newKey = { frame: 0, value: keys[0].value };
  47157. keys.splice(0, 0, newKey);
  47158. }
  47159. // Check limits
  47160. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47161. from = keys[0].frame;
  47162. }
  47163. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47164. to = keys[keys.length - 1].frame;
  47165. }
  47166. //to and from cannot be the same key
  47167. if (from === to) {
  47168. if (from > keys[0].frame) {
  47169. from--;
  47170. }
  47171. else if (to < keys[keys.length - 1].frame) {
  47172. to++;
  47173. }
  47174. }
  47175. // Compute ratio
  47176. var range = to - from;
  47177. var offsetValue;
  47178. // ratio represents the frame delta between from and to
  47179. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47180. var highLimitValue = 0;
  47181. this._previousDelay = delay;
  47182. this._previousRatio = ratio;
  47183. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47184. returnValue = false;
  47185. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47186. }
  47187. else {
  47188. // Get max value if required
  47189. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47190. var keyOffset = to.toString() + from.toString();
  47191. if (!this._offsetsCache[keyOffset]) {
  47192. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47193. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47194. switch (this._animation.dataType) {
  47195. // Float
  47196. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47197. this._offsetsCache[keyOffset] = toValue - fromValue;
  47198. break;
  47199. // Quaternion
  47200. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47201. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47202. break;
  47203. // Vector3
  47204. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47205. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47206. // Vector2
  47207. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47208. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47209. // Size
  47210. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47211. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47212. // Color3
  47213. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47214. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47215. default:
  47216. break;
  47217. }
  47218. this._highLimitsCache[keyOffset] = toValue;
  47219. }
  47220. highLimitValue = this._highLimitsCache[keyOffset];
  47221. offsetValue = this._offsetsCache[keyOffset];
  47222. }
  47223. }
  47224. if (offsetValue === undefined) {
  47225. switch (this._animation.dataType) {
  47226. // Float
  47227. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47228. offsetValue = 0;
  47229. break;
  47230. // Quaternion
  47231. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47232. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47233. break;
  47234. // Vector3
  47235. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47236. offsetValue = BABYLON.Vector3.Zero();
  47237. break;
  47238. // Vector2
  47239. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47240. offsetValue = BABYLON.Vector2.Zero();
  47241. break;
  47242. // Size
  47243. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47244. offsetValue = BABYLON.Size.Zero();
  47245. break;
  47246. // Color3
  47247. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47248. offsetValue = BABYLON.Color3.Black();
  47249. }
  47250. }
  47251. // Compute value
  47252. var repeatCount = (ratio / range) >> 0;
  47253. var currentFrame = returnValue ? from + ratio % range : to;
  47254. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47255. // Set value
  47256. this.setValue(currentValue);
  47257. // Check events
  47258. var events = this._animation.getEvents();
  47259. for (var index = 0; index < events.length; index++) {
  47260. // Make sure current frame has passed event frame and that event frame is within the current range
  47261. // Also, handle both forward and reverse animations
  47262. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47263. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47264. var event = events[index];
  47265. if (!event.isDone) {
  47266. // If event should be done only once, remove it.
  47267. if (event.onlyOnce) {
  47268. events.splice(index, 1);
  47269. index--;
  47270. }
  47271. event.isDone = true;
  47272. event.action();
  47273. } // Don't do anything if the event has already be done.
  47274. }
  47275. else if (events[index].isDone && !events[index].onlyOnce) {
  47276. // reset event, the animation is looping
  47277. events[index].isDone = false;
  47278. }
  47279. }
  47280. if (!returnValue) {
  47281. this._stopped = true;
  47282. }
  47283. return returnValue;
  47284. };
  47285. return RuntimeAnimation;
  47286. }());
  47287. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47288. })(BABYLON || (BABYLON = {}));
  47289. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47290. var BABYLON;
  47291. (function (BABYLON) {
  47292. var Animatable = /** @class */ (function () {
  47293. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47294. if (fromFrame === void 0) { fromFrame = 0; }
  47295. if (toFrame === void 0) { toFrame = 100; }
  47296. if (loopAnimation === void 0) { loopAnimation = false; }
  47297. if (speedRatio === void 0) { speedRatio = 1.0; }
  47298. this.target = target;
  47299. this.fromFrame = fromFrame;
  47300. this.toFrame = toFrame;
  47301. this.loopAnimation = loopAnimation;
  47302. this.onAnimationEnd = onAnimationEnd;
  47303. this._localDelayOffset = null;
  47304. this._pausedDelay = null;
  47305. this._runtimeAnimations = new Array();
  47306. this._paused = false;
  47307. this._speedRatio = 1;
  47308. this.animationStarted = false;
  47309. if (animations) {
  47310. this.appendAnimations(target, animations);
  47311. }
  47312. this._speedRatio = speedRatio;
  47313. this._scene = scene;
  47314. scene._activeAnimatables.push(this);
  47315. }
  47316. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47317. get: function () {
  47318. return this._speedRatio;
  47319. },
  47320. set: function (value) {
  47321. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47322. var animation = this._runtimeAnimations[index];
  47323. animation._prepareForSpeedRatioChange(value);
  47324. }
  47325. this._speedRatio = value;
  47326. },
  47327. enumerable: true,
  47328. configurable: true
  47329. });
  47330. // Methods
  47331. Animatable.prototype.getAnimations = function () {
  47332. return this._runtimeAnimations;
  47333. };
  47334. Animatable.prototype.appendAnimations = function (target, animations) {
  47335. for (var index = 0; index < animations.length; index++) {
  47336. var animation = animations[index];
  47337. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47338. }
  47339. };
  47340. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47341. var runtimeAnimations = this._runtimeAnimations;
  47342. for (var index = 0; index < runtimeAnimations.length; index++) {
  47343. if (runtimeAnimations[index].animation.targetProperty === property) {
  47344. return runtimeAnimations[index].animation;
  47345. }
  47346. }
  47347. return null;
  47348. };
  47349. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47350. var runtimeAnimations = this._runtimeAnimations;
  47351. for (var index = 0; index < runtimeAnimations.length; index++) {
  47352. if (runtimeAnimations[index].animation.targetProperty === property) {
  47353. return runtimeAnimations[index];
  47354. }
  47355. }
  47356. return null;
  47357. };
  47358. Animatable.prototype.reset = function () {
  47359. var runtimeAnimations = this._runtimeAnimations;
  47360. for (var index = 0; index < runtimeAnimations.length; index++) {
  47361. runtimeAnimations[index].reset();
  47362. }
  47363. // Reset to original value
  47364. for (index = 0; index < runtimeAnimations.length; index++) {
  47365. var animation = runtimeAnimations[index];
  47366. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47367. }
  47368. this._localDelayOffset = null;
  47369. this._pausedDelay = null;
  47370. };
  47371. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47372. var runtimeAnimations = this._runtimeAnimations;
  47373. for (var index = 0; index < runtimeAnimations.length; index++) {
  47374. runtimeAnimations[index].animation.enableBlending = true;
  47375. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47376. }
  47377. };
  47378. Animatable.prototype.disableBlending = function () {
  47379. var runtimeAnimations = this._runtimeAnimations;
  47380. for (var index = 0; index < runtimeAnimations.length; index++) {
  47381. runtimeAnimations[index].animation.enableBlending = false;
  47382. }
  47383. };
  47384. Animatable.prototype.goToFrame = function (frame) {
  47385. var runtimeAnimations = this._runtimeAnimations;
  47386. if (runtimeAnimations[0]) {
  47387. var fps = runtimeAnimations[0].animation.framePerSecond;
  47388. var currentFrame = runtimeAnimations[0].currentFrame;
  47389. var adjustTime = frame - currentFrame;
  47390. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47391. if (this._localDelayOffset === null) {
  47392. this._localDelayOffset = 0;
  47393. }
  47394. this._localDelayOffset -= delay;
  47395. }
  47396. for (var index = 0; index < runtimeAnimations.length; index++) {
  47397. runtimeAnimations[index].goToFrame(frame);
  47398. }
  47399. };
  47400. Animatable.prototype.pause = function () {
  47401. if (this._paused) {
  47402. return;
  47403. }
  47404. this._paused = true;
  47405. };
  47406. Animatable.prototype.restart = function () {
  47407. this._paused = false;
  47408. };
  47409. Animatable.prototype.stop = function (animationName) {
  47410. if (animationName) {
  47411. var idx = this._scene._activeAnimatables.indexOf(this);
  47412. if (idx > -1) {
  47413. var runtimeAnimations = this._runtimeAnimations;
  47414. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47415. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47416. continue;
  47417. }
  47418. runtimeAnimations[index].dispose();
  47419. runtimeAnimations.splice(index, 1);
  47420. }
  47421. if (runtimeAnimations.length == 0) {
  47422. this._scene._activeAnimatables.splice(idx, 1);
  47423. if (this.onAnimationEnd) {
  47424. this.onAnimationEnd();
  47425. }
  47426. }
  47427. }
  47428. }
  47429. else {
  47430. var index = this._scene._activeAnimatables.indexOf(this);
  47431. if (index > -1) {
  47432. this._scene._activeAnimatables.splice(index, 1);
  47433. var runtimeAnimations = this._runtimeAnimations;
  47434. for (var index = 0; index < runtimeAnimations.length; index++) {
  47435. runtimeAnimations[index].dispose();
  47436. }
  47437. if (this.onAnimationEnd) {
  47438. this.onAnimationEnd();
  47439. }
  47440. }
  47441. }
  47442. };
  47443. Animatable.prototype._animate = function (delay) {
  47444. if (this._paused) {
  47445. this.animationStarted = false;
  47446. if (this._pausedDelay === null) {
  47447. this._pausedDelay = delay;
  47448. }
  47449. return true;
  47450. }
  47451. if (this._localDelayOffset === null) {
  47452. this._localDelayOffset = delay;
  47453. this._pausedDelay = null;
  47454. }
  47455. else if (this._pausedDelay !== null) {
  47456. this._localDelayOffset += delay - this._pausedDelay;
  47457. this._pausedDelay = null;
  47458. }
  47459. // Animating
  47460. var running = false;
  47461. var runtimeAnimations = this._runtimeAnimations;
  47462. var index;
  47463. for (index = 0; index < runtimeAnimations.length; index++) {
  47464. var animation = runtimeAnimations[index];
  47465. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47466. running = running || isRunning;
  47467. }
  47468. this.animationStarted = running;
  47469. if (!running) {
  47470. // Remove from active animatables
  47471. index = this._scene._activeAnimatables.indexOf(this);
  47472. this._scene._activeAnimatables.splice(index, 1);
  47473. // Dispose all runtime animations
  47474. for (index = 0; index < runtimeAnimations.length; index++) {
  47475. runtimeAnimations[index].dispose();
  47476. }
  47477. }
  47478. if (!running && this.onAnimationEnd) {
  47479. this.onAnimationEnd();
  47480. this.onAnimationEnd = null;
  47481. }
  47482. return running;
  47483. };
  47484. return Animatable;
  47485. }());
  47486. BABYLON.Animatable = Animatable;
  47487. })(BABYLON || (BABYLON = {}));
  47488. //# sourceMappingURL=babylon.animatable.js.map
  47489. var BABYLON;
  47490. (function (BABYLON) {
  47491. var EasingFunction = /** @class */ (function () {
  47492. function EasingFunction() {
  47493. // Properties
  47494. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47495. }
  47496. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47497. get: function () {
  47498. return EasingFunction._EASINGMODE_EASEIN;
  47499. },
  47500. enumerable: true,
  47501. configurable: true
  47502. });
  47503. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47504. get: function () {
  47505. return EasingFunction._EASINGMODE_EASEOUT;
  47506. },
  47507. enumerable: true,
  47508. configurable: true
  47509. });
  47510. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47511. get: function () {
  47512. return EasingFunction._EASINGMODE_EASEINOUT;
  47513. },
  47514. enumerable: true,
  47515. configurable: true
  47516. });
  47517. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47518. var n = Math.min(Math.max(easingMode, 0), 2);
  47519. this._easingMode = n;
  47520. };
  47521. EasingFunction.prototype.getEasingMode = function () {
  47522. return this._easingMode;
  47523. };
  47524. EasingFunction.prototype.easeInCore = function (gradient) {
  47525. throw new Error('You must implement this method');
  47526. };
  47527. EasingFunction.prototype.ease = function (gradient) {
  47528. switch (this._easingMode) {
  47529. case EasingFunction.EASINGMODE_EASEIN:
  47530. return this.easeInCore(gradient);
  47531. case EasingFunction.EASINGMODE_EASEOUT:
  47532. return (1 - this.easeInCore(1 - gradient));
  47533. }
  47534. if (gradient >= 0.5) {
  47535. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47536. }
  47537. return (this.easeInCore(gradient * 2) * 0.5);
  47538. };
  47539. //Statics
  47540. EasingFunction._EASINGMODE_EASEIN = 0;
  47541. EasingFunction._EASINGMODE_EASEOUT = 1;
  47542. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47543. return EasingFunction;
  47544. }());
  47545. BABYLON.EasingFunction = EasingFunction;
  47546. var CircleEase = /** @class */ (function (_super) {
  47547. __extends(CircleEase, _super);
  47548. function CircleEase() {
  47549. return _super !== null && _super.apply(this, arguments) || this;
  47550. }
  47551. CircleEase.prototype.easeInCore = function (gradient) {
  47552. gradient = Math.max(0, Math.min(1, gradient));
  47553. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47554. };
  47555. return CircleEase;
  47556. }(EasingFunction));
  47557. BABYLON.CircleEase = CircleEase;
  47558. var BackEase = /** @class */ (function (_super) {
  47559. __extends(BackEase, _super);
  47560. function BackEase(amplitude) {
  47561. if (amplitude === void 0) { amplitude = 1; }
  47562. var _this = _super.call(this) || this;
  47563. _this.amplitude = amplitude;
  47564. return _this;
  47565. }
  47566. BackEase.prototype.easeInCore = function (gradient) {
  47567. var num = Math.max(0, this.amplitude);
  47568. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47569. };
  47570. return BackEase;
  47571. }(EasingFunction));
  47572. BABYLON.BackEase = BackEase;
  47573. var BounceEase = /** @class */ (function (_super) {
  47574. __extends(BounceEase, _super);
  47575. function BounceEase(bounces, bounciness) {
  47576. if (bounces === void 0) { bounces = 3; }
  47577. if (bounciness === void 0) { bounciness = 2; }
  47578. var _this = _super.call(this) || this;
  47579. _this.bounces = bounces;
  47580. _this.bounciness = bounciness;
  47581. return _this;
  47582. }
  47583. BounceEase.prototype.easeInCore = function (gradient) {
  47584. var y = Math.max(0.0, this.bounces);
  47585. var bounciness = this.bounciness;
  47586. if (bounciness <= 1.0) {
  47587. bounciness = 1.001;
  47588. }
  47589. var num9 = Math.pow(bounciness, y);
  47590. var num5 = 1.0 - bounciness;
  47591. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47592. var num15 = gradient * num4;
  47593. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47594. var num3 = Math.floor(num65);
  47595. var num13 = num3 + 1.0;
  47596. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47597. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47598. var num7 = (num8 + num12) * 0.5;
  47599. var num6 = gradient - num7;
  47600. var num2 = num7 - num8;
  47601. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47602. };
  47603. return BounceEase;
  47604. }(EasingFunction));
  47605. BABYLON.BounceEase = BounceEase;
  47606. var CubicEase = /** @class */ (function (_super) {
  47607. __extends(CubicEase, _super);
  47608. function CubicEase() {
  47609. return _super !== null && _super.apply(this, arguments) || this;
  47610. }
  47611. CubicEase.prototype.easeInCore = function (gradient) {
  47612. return (gradient * gradient * gradient);
  47613. };
  47614. return CubicEase;
  47615. }(EasingFunction));
  47616. BABYLON.CubicEase = CubicEase;
  47617. var ElasticEase = /** @class */ (function (_super) {
  47618. __extends(ElasticEase, _super);
  47619. function ElasticEase(oscillations, springiness) {
  47620. if (oscillations === void 0) { oscillations = 3; }
  47621. if (springiness === void 0) { springiness = 3; }
  47622. var _this = _super.call(this) || this;
  47623. _this.oscillations = oscillations;
  47624. _this.springiness = springiness;
  47625. return _this;
  47626. }
  47627. ElasticEase.prototype.easeInCore = function (gradient) {
  47628. var num2;
  47629. var num3 = Math.max(0.0, this.oscillations);
  47630. var num = Math.max(0.0, this.springiness);
  47631. if (num == 0) {
  47632. num2 = gradient;
  47633. }
  47634. else {
  47635. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47636. }
  47637. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47638. };
  47639. return ElasticEase;
  47640. }(EasingFunction));
  47641. BABYLON.ElasticEase = ElasticEase;
  47642. var ExponentialEase = /** @class */ (function (_super) {
  47643. __extends(ExponentialEase, _super);
  47644. function ExponentialEase(exponent) {
  47645. if (exponent === void 0) { exponent = 2; }
  47646. var _this = _super.call(this) || this;
  47647. _this.exponent = exponent;
  47648. return _this;
  47649. }
  47650. ExponentialEase.prototype.easeInCore = function (gradient) {
  47651. if (this.exponent <= 0) {
  47652. return gradient;
  47653. }
  47654. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47655. };
  47656. return ExponentialEase;
  47657. }(EasingFunction));
  47658. BABYLON.ExponentialEase = ExponentialEase;
  47659. var PowerEase = /** @class */ (function (_super) {
  47660. __extends(PowerEase, _super);
  47661. function PowerEase(power) {
  47662. if (power === void 0) { power = 2; }
  47663. var _this = _super.call(this) || this;
  47664. _this.power = power;
  47665. return _this;
  47666. }
  47667. PowerEase.prototype.easeInCore = function (gradient) {
  47668. var y = Math.max(0.0, this.power);
  47669. return Math.pow(gradient, y);
  47670. };
  47671. return PowerEase;
  47672. }(EasingFunction));
  47673. BABYLON.PowerEase = PowerEase;
  47674. var QuadraticEase = /** @class */ (function (_super) {
  47675. __extends(QuadraticEase, _super);
  47676. function QuadraticEase() {
  47677. return _super !== null && _super.apply(this, arguments) || this;
  47678. }
  47679. QuadraticEase.prototype.easeInCore = function (gradient) {
  47680. return (gradient * gradient);
  47681. };
  47682. return QuadraticEase;
  47683. }(EasingFunction));
  47684. BABYLON.QuadraticEase = QuadraticEase;
  47685. var QuarticEase = /** @class */ (function (_super) {
  47686. __extends(QuarticEase, _super);
  47687. function QuarticEase() {
  47688. return _super !== null && _super.apply(this, arguments) || this;
  47689. }
  47690. QuarticEase.prototype.easeInCore = function (gradient) {
  47691. return (gradient * gradient * gradient * gradient);
  47692. };
  47693. return QuarticEase;
  47694. }(EasingFunction));
  47695. BABYLON.QuarticEase = QuarticEase;
  47696. var QuinticEase = /** @class */ (function (_super) {
  47697. __extends(QuinticEase, _super);
  47698. function QuinticEase() {
  47699. return _super !== null && _super.apply(this, arguments) || this;
  47700. }
  47701. QuinticEase.prototype.easeInCore = function (gradient) {
  47702. return (gradient * gradient * gradient * gradient * gradient);
  47703. };
  47704. return QuinticEase;
  47705. }(EasingFunction));
  47706. BABYLON.QuinticEase = QuinticEase;
  47707. var SineEase = /** @class */ (function (_super) {
  47708. __extends(SineEase, _super);
  47709. function SineEase() {
  47710. return _super !== null && _super.apply(this, arguments) || this;
  47711. }
  47712. SineEase.prototype.easeInCore = function (gradient) {
  47713. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47714. };
  47715. return SineEase;
  47716. }(EasingFunction));
  47717. BABYLON.SineEase = SineEase;
  47718. var BezierCurveEase = /** @class */ (function (_super) {
  47719. __extends(BezierCurveEase, _super);
  47720. function BezierCurveEase(x1, y1, x2, y2) {
  47721. if (x1 === void 0) { x1 = 0; }
  47722. if (y1 === void 0) { y1 = 0; }
  47723. if (x2 === void 0) { x2 = 1; }
  47724. if (y2 === void 0) { y2 = 1; }
  47725. var _this = _super.call(this) || this;
  47726. _this.x1 = x1;
  47727. _this.y1 = y1;
  47728. _this.x2 = x2;
  47729. _this.y2 = y2;
  47730. return _this;
  47731. }
  47732. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47733. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47734. };
  47735. return BezierCurveEase;
  47736. }(EasingFunction));
  47737. BABYLON.BezierCurveEase = BezierCurveEase;
  47738. })(BABYLON || (BABYLON = {}));
  47739. //# sourceMappingURL=babylon.easing.js.map
  47740. var BABYLON;
  47741. (function (BABYLON) {
  47742. var Condition = /** @class */ (function () {
  47743. function Condition(actionManager) {
  47744. this._actionManager = actionManager;
  47745. }
  47746. Condition.prototype.isValid = function () {
  47747. return true;
  47748. };
  47749. Condition.prototype._getProperty = function (propertyPath) {
  47750. return this._actionManager._getProperty(propertyPath);
  47751. };
  47752. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47753. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47754. };
  47755. Condition.prototype.serialize = function () {
  47756. };
  47757. Condition.prototype._serialize = function (serializedCondition) {
  47758. return {
  47759. type: 2,
  47760. children: [],
  47761. name: serializedCondition.name,
  47762. properties: serializedCondition.properties
  47763. };
  47764. };
  47765. return Condition;
  47766. }());
  47767. BABYLON.Condition = Condition;
  47768. var ValueCondition = /** @class */ (function (_super) {
  47769. __extends(ValueCondition, _super);
  47770. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47771. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47772. var _this = _super.call(this, actionManager) || this;
  47773. _this.propertyPath = propertyPath;
  47774. _this.value = value;
  47775. _this.operator = operator;
  47776. _this._target = target;
  47777. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47778. _this._property = _this._getProperty(_this.propertyPath);
  47779. return _this;
  47780. }
  47781. Object.defineProperty(ValueCondition, "IsEqual", {
  47782. get: function () {
  47783. return ValueCondition._IsEqual;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(ValueCondition, "IsDifferent", {
  47789. get: function () {
  47790. return ValueCondition._IsDifferent;
  47791. },
  47792. enumerable: true,
  47793. configurable: true
  47794. });
  47795. Object.defineProperty(ValueCondition, "IsGreater", {
  47796. get: function () {
  47797. return ValueCondition._IsGreater;
  47798. },
  47799. enumerable: true,
  47800. configurable: true
  47801. });
  47802. Object.defineProperty(ValueCondition, "IsLesser", {
  47803. get: function () {
  47804. return ValueCondition._IsLesser;
  47805. },
  47806. enumerable: true,
  47807. configurable: true
  47808. });
  47809. // Methods
  47810. ValueCondition.prototype.isValid = function () {
  47811. switch (this.operator) {
  47812. case ValueCondition.IsGreater:
  47813. return this._effectiveTarget[this._property] > this.value;
  47814. case ValueCondition.IsLesser:
  47815. return this._effectiveTarget[this._property] < this.value;
  47816. case ValueCondition.IsEqual:
  47817. case ValueCondition.IsDifferent:
  47818. var check;
  47819. if (this.value.equals) {
  47820. check = this.value.equals(this._effectiveTarget[this._property]);
  47821. }
  47822. else {
  47823. check = this.value === this._effectiveTarget[this._property];
  47824. }
  47825. return this.operator === ValueCondition.IsEqual ? check : !check;
  47826. }
  47827. return false;
  47828. };
  47829. ValueCondition.prototype.serialize = function () {
  47830. return this._serialize({
  47831. name: "ValueCondition",
  47832. properties: [
  47833. BABYLON.Action._GetTargetProperty(this._target),
  47834. { name: "propertyPath", value: this.propertyPath },
  47835. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47836. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47837. ]
  47838. });
  47839. };
  47840. ValueCondition.GetOperatorName = function (operator) {
  47841. switch (operator) {
  47842. case ValueCondition._IsEqual: return "IsEqual";
  47843. case ValueCondition._IsDifferent: return "IsDifferent";
  47844. case ValueCondition._IsGreater: return "IsGreater";
  47845. case ValueCondition._IsLesser: return "IsLesser";
  47846. default: return "";
  47847. }
  47848. };
  47849. // Statics
  47850. ValueCondition._IsEqual = 0;
  47851. ValueCondition._IsDifferent = 1;
  47852. ValueCondition._IsGreater = 2;
  47853. ValueCondition._IsLesser = 3;
  47854. return ValueCondition;
  47855. }(Condition));
  47856. BABYLON.ValueCondition = ValueCondition;
  47857. var PredicateCondition = /** @class */ (function (_super) {
  47858. __extends(PredicateCondition, _super);
  47859. function PredicateCondition(actionManager, predicate) {
  47860. var _this = _super.call(this, actionManager) || this;
  47861. _this.predicate = predicate;
  47862. return _this;
  47863. }
  47864. PredicateCondition.prototype.isValid = function () {
  47865. return this.predicate();
  47866. };
  47867. return PredicateCondition;
  47868. }(Condition));
  47869. BABYLON.PredicateCondition = PredicateCondition;
  47870. var StateCondition = /** @class */ (function (_super) {
  47871. __extends(StateCondition, _super);
  47872. function StateCondition(actionManager, target, value) {
  47873. var _this = _super.call(this, actionManager) || this;
  47874. _this.value = value;
  47875. _this._target = target;
  47876. return _this;
  47877. }
  47878. // Methods
  47879. StateCondition.prototype.isValid = function () {
  47880. return this._target.state === this.value;
  47881. };
  47882. StateCondition.prototype.serialize = function () {
  47883. return this._serialize({
  47884. name: "StateCondition",
  47885. properties: [
  47886. BABYLON.Action._GetTargetProperty(this._target),
  47887. { name: "value", value: this.value }
  47888. ]
  47889. });
  47890. };
  47891. return StateCondition;
  47892. }(Condition));
  47893. BABYLON.StateCondition = StateCondition;
  47894. })(BABYLON || (BABYLON = {}));
  47895. //# sourceMappingURL=babylon.condition.js.map
  47896. var BABYLON;
  47897. (function (BABYLON) {
  47898. var Action = /** @class */ (function () {
  47899. function Action(triggerOptions, condition) {
  47900. this.triggerOptions = triggerOptions;
  47901. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47902. if (triggerOptions.parameter) {
  47903. this.trigger = triggerOptions.trigger;
  47904. this._triggerParameter = triggerOptions.parameter;
  47905. }
  47906. else {
  47907. this.trigger = triggerOptions;
  47908. }
  47909. this._nextActiveAction = this;
  47910. this._condition = condition;
  47911. }
  47912. // Methods
  47913. Action.prototype._prepare = function () {
  47914. };
  47915. Action.prototype.getTriggerParameter = function () {
  47916. return this._triggerParameter;
  47917. };
  47918. Action.prototype._executeCurrent = function (evt) {
  47919. if (this._nextActiveAction._condition) {
  47920. var condition = this._nextActiveAction._condition;
  47921. var currentRenderId = this._actionManager.getScene().getRenderId();
  47922. // We cache the current evaluation for the current frame
  47923. if (condition._evaluationId === currentRenderId) {
  47924. if (!condition._currentResult) {
  47925. return;
  47926. }
  47927. }
  47928. else {
  47929. condition._evaluationId = currentRenderId;
  47930. if (!condition.isValid()) {
  47931. condition._currentResult = false;
  47932. return;
  47933. }
  47934. condition._currentResult = true;
  47935. }
  47936. }
  47937. this.onBeforeExecuteObservable.notifyObservers(this);
  47938. this._nextActiveAction.execute(evt);
  47939. this.skipToNextActiveAction();
  47940. };
  47941. Action.prototype.execute = function (evt) {
  47942. };
  47943. Action.prototype.skipToNextActiveAction = function () {
  47944. if (this._nextActiveAction._child) {
  47945. if (!this._nextActiveAction._child._actionManager) {
  47946. this._nextActiveAction._child._actionManager = this._actionManager;
  47947. }
  47948. this._nextActiveAction = this._nextActiveAction._child;
  47949. }
  47950. else {
  47951. this._nextActiveAction = this;
  47952. }
  47953. };
  47954. Action.prototype.then = function (action) {
  47955. this._child = action;
  47956. action._actionManager = this._actionManager;
  47957. action._prepare();
  47958. return action;
  47959. };
  47960. Action.prototype._getProperty = function (propertyPath) {
  47961. return this._actionManager._getProperty(propertyPath);
  47962. };
  47963. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47964. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47965. };
  47966. Action.prototype.serialize = function (parent) {
  47967. };
  47968. // Called by BABYLON.Action objects in serialize(...). Internal use
  47969. Action.prototype._serialize = function (serializedAction, parent) {
  47970. var serializationObject = {
  47971. type: 1,
  47972. children: [],
  47973. name: serializedAction.name,
  47974. properties: serializedAction.properties || []
  47975. };
  47976. // Serialize child
  47977. if (this._child) {
  47978. this._child.serialize(serializationObject);
  47979. }
  47980. // Check if "this" has a condition
  47981. if (this._condition) {
  47982. var serializedCondition = this._condition.serialize();
  47983. serializedCondition.children.push(serializationObject);
  47984. if (parent) {
  47985. parent.children.push(serializedCondition);
  47986. }
  47987. return serializedCondition;
  47988. }
  47989. if (parent) {
  47990. parent.children.push(serializationObject);
  47991. }
  47992. return serializationObject;
  47993. };
  47994. Action._SerializeValueAsString = function (value) {
  47995. if (typeof value === "number") {
  47996. return value.toString();
  47997. }
  47998. if (typeof value === "boolean") {
  47999. return value ? "true" : "false";
  48000. }
  48001. if (value instanceof BABYLON.Vector2) {
  48002. return value.x + ", " + value.y;
  48003. }
  48004. if (value instanceof BABYLON.Vector3) {
  48005. return value.x + ", " + value.y + ", " + value.z;
  48006. }
  48007. if (value instanceof BABYLON.Color3) {
  48008. return value.r + ", " + value.g + ", " + value.b;
  48009. }
  48010. if (value instanceof BABYLON.Color4) {
  48011. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48012. }
  48013. return value; // string
  48014. };
  48015. Action._GetTargetProperty = function (target) {
  48016. return {
  48017. name: "target",
  48018. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48019. : target instanceof BABYLON.Light ? "LightProperties"
  48020. : target instanceof BABYLON.Camera ? "CameraProperties"
  48021. : "SceneProperties",
  48022. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48023. };
  48024. };
  48025. return Action;
  48026. }());
  48027. BABYLON.Action = Action;
  48028. })(BABYLON || (BABYLON = {}));
  48029. //# sourceMappingURL=babylon.action.js.map
  48030. var BABYLON;
  48031. (function (BABYLON) {
  48032. /**
  48033. * ActionEvent is the event beint sent when an action is triggered.
  48034. */
  48035. var ActionEvent = /** @class */ (function () {
  48036. /**
  48037. * @param source The mesh or sprite that triggered the action.
  48038. * @param pointerX The X mouse cursor position at the time of the event
  48039. * @param pointerY The Y mouse cursor position at the time of the event
  48040. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48041. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48042. */
  48043. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48044. this.source = source;
  48045. this.pointerX = pointerX;
  48046. this.pointerY = pointerY;
  48047. this.meshUnderPointer = meshUnderPointer;
  48048. this.sourceEvent = sourceEvent;
  48049. this.additionalData = additionalData;
  48050. }
  48051. /**
  48052. * Helper function to auto-create an ActionEvent from a source mesh.
  48053. * @param source The source mesh that triggered the event
  48054. * @param evt {Event} The original (browser) event
  48055. */
  48056. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48057. var scene = source.getScene();
  48058. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48059. };
  48060. /**
  48061. * Helper function to auto-create an ActionEvent from a source mesh.
  48062. * @param source The source sprite that triggered the event
  48063. * @param scene Scene associated with the sprite
  48064. * @param evt {Event} The original (browser) event
  48065. */
  48066. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48067. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48068. };
  48069. /**
  48070. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48071. * @param scene the scene where the event occurred
  48072. * @param evt {Event} The original (browser) event
  48073. */
  48074. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48075. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48076. };
  48077. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48078. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48079. };
  48080. return ActionEvent;
  48081. }());
  48082. BABYLON.ActionEvent = ActionEvent;
  48083. /**
  48084. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48085. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48086. */
  48087. var ActionManager = /** @class */ (function () {
  48088. function ActionManager(scene) {
  48089. // Members
  48090. this.actions = new Array();
  48091. this.hoverCursor = '';
  48092. this._scene = scene;
  48093. scene._actionManagers.push(this);
  48094. }
  48095. Object.defineProperty(ActionManager, "NothingTrigger", {
  48096. get: function () {
  48097. return ActionManager._NothingTrigger;
  48098. },
  48099. enumerable: true,
  48100. configurable: true
  48101. });
  48102. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48103. get: function () {
  48104. return ActionManager._OnPickTrigger;
  48105. },
  48106. enumerable: true,
  48107. configurable: true
  48108. });
  48109. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48110. get: function () {
  48111. return ActionManager._OnLeftPickTrigger;
  48112. },
  48113. enumerable: true,
  48114. configurable: true
  48115. });
  48116. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48117. get: function () {
  48118. return ActionManager._OnRightPickTrigger;
  48119. },
  48120. enumerable: true,
  48121. configurable: true
  48122. });
  48123. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48124. get: function () {
  48125. return ActionManager._OnCenterPickTrigger;
  48126. },
  48127. enumerable: true,
  48128. configurable: true
  48129. });
  48130. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48131. get: function () {
  48132. return ActionManager._OnPickDownTrigger;
  48133. },
  48134. enumerable: true,
  48135. configurable: true
  48136. });
  48137. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48138. get: function () {
  48139. return ActionManager._OnDoublePickTrigger;
  48140. },
  48141. enumerable: true,
  48142. configurable: true
  48143. });
  48144. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48145. get: function () {
  48146. return ActionManager._OnPickUpTrigger;
  48147. },
  48148. enumerable: true,
  48149. configurable: true
  48150. });
  48151. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48152. /// This trigger will only be raised if you also declared a OnPickDown
  48153. get: function () {
  48154. return ActionManager._OnPickOutTrigger;
  48155. },
  48156. enumerable: true,
  48157. configurable: true
  48158. });
  48159. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48160. get: function () {
  48161. return ActionManager._OnLongPressTrigger;
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48167. get: function () {
  48168. return ActionManager._OnPointerOverTrigger;
  48169. },
  48170. enumerable: true,
  48171. configurable: true
  48172. });
  48173. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48174. get: function () {
  48175. return ActionManager._OnPointerOutTrigger;
  48176. },
  48177. enumerable: true,
  48178. configurable: true
  48179. });
  48180. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48181. get: function () {
  48182. return ActionManager._OnEveryFrameTrigger;
  48183. },
  48184. enumerable: true,
  48185. configurable: true
  48186. });
  48187. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48188. get: function () {
  48189. return ActionManager._OnIntersectionEnterTrigger;
  48190. },
  48191. enumerable: true,
  48192. configurable: true
  48193. });
  48194. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48195. get: function () {
  48196. return ActionManager._OnIntersectionExitTrigger;
  48197. },
  48198. enumerable: true,
  48199. configurable: true
  48200. });
  48201. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48202. get: function () {
  48203. return ActionManager._OnKeyDownTrigger;
  48204. },
  48205. enumerable: true,
  48206. configurable: true
  48207. });
  48208. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48209. get: function () {
  48210. return ActionManager._OnKeyUpTrigger;
  48211. },
  48212. enumerable: true,
  48213. configurable: true
  48214. });
  48215. // Methods
  48216. ActionManager.prototype.dispose = function () {
  48217. var index = this._scene._actionManagers.indexOf(this);
  48218. for (var i = 0; i < this.actions.length; i++) {
  48219. var action = this.actions[i];
  48220. ActionManager.Triggers[action.trigger]--;
  48221. if (ActionManager.Triggers[action.trigger] === 0) {
  48222. delete ActionManager.Triggers[action.trigger];
  48223. }
  48224. }
  48225. if (index > -1) {
  48226. this._scene._actionManagers.splice(index, 1);
  48227. }
  48228. };
  48229. ActionManager.prototype.getScene = function () {
  48230. return this._scene;
  48231. };
  48232. /**
  48233. * Does this action manager handles actions of any of the given triggers
  48234. * @param {number[]} triggers - the triggers to be tested
  48235. * @return {boolean} whether one (or more) of the triggers is handeled
  48236. */
  48237. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48238. for (var index = 0; index < this.actions.length; index++) {
  48239. var action = this.actions[index];
  48240. if (triggers.indexOf(action.trigger) > -1) {
  48241. return true;
  48242. }
  48243. }
  48244. return false;
  48245. };
  48246. /**
  48247. * Does this action manager handles actions of a given trigger
  48248. * @param {number} trigger - the trigger to be tested
  48249. * @return {boolean} whether the trigger is handeled
  48250. */
  48251. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48252. for (var index = 0; index < this.actions.length; index++) {
  48253. var action = this.actions[index];
  48254. if (action.trigger === trigger) {
  48255. return true;
  48256. }
  48257. }
  48258. return false;
  48259. };
  48260. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48261. /**
  48262. * Does this action manager has pointer triggers
  48263. * @return {boolean} whether or not it has pointer triggers
  48264. */
  48265. get: function () {
  48266. for (var index = 0; index < this.actions.length; index++) {
  48267. var action = this.actions[index];
  48268. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48269. return true;
  48270. }
  48271. }
  48272. return false;
  48273. },
  48274. enumerable: true,
  48275. configurable: true
  48276. });
  48277. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48278. /**
  48279. * Does this action manager has pick triggers
  48280. * @return {boolean} whether or not it has pick triggers
  48281. */
  48282. get: function () {
  48283. for (var index = 0; index < this.actions.length; index++) {
  48284. var action = this.actions[index];
  48285. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48286. return true;
  48287. }
  48288. }
  48289. return false;
  48290. },
  48291. enumerable: true,
  48292. configurable: true
  48293. });
  48294. Object.defineProperty(ActionManager, "HasTriggers", {
  48295. /**
  48296. * Does exist one action manager with at least one trigger
  48297. * @return {boolean} whether or not it exists one action manager with one trigger
  48298. **/
  48299. get: function () {
  48300. for (var t in ActionManager.Triggers) {
  48301. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48302. return true;
  48303. }
  48304. }
  48305. return false;
  48306. },
  48307. enumerable: true,
  48308. configurable: true
  48309. });
  48310. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48311. /**
  48312. * Does exist one action manager with at least one pick trigger
  48313. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48314. **/
  48315. get: function () {
  48316. for (var t in ActionManager.Triggers) {
  48317. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48318. var t_int = parseInt(t);
  48319. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48320. return true;
  48321. }
  48322. }
  48323. }
  48324. return false;
  48325. },
  48326. enumerable: true,
  48327. configurable: true
  48328. });
  48329. /**
  48330. * Does exist one action manager that handles actions of a given trigger
  48331. * @param {number} trigger - the trigger to be tested
  48332. * @return {boolean} whether the trigger is handeled by at least one action manager
  48333. **/
  48334. ActionManager.HasSpecificTrigger = function (trigger) {
  48335. for (var t in ActionManager.Triggers) {
  48336. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48337. var t_int = parseInt(t);
  48338. if (t_int === trigger) {
  48339. return true;
  48340. }
  48341. }
  48342. }
  48343. return false;
  48344. };
  48345. /**
  48346. * Registers an action to this action manager
  48347. * @param {BABYLON.Action} action - the action to be registered
  48348. * @return {BABYLON.Action} the action amended (prepared) after registration
  48349. */
  48350. ActionManager.prototype.registerAction = function (action) {
  48351. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48352. if (this.getScene().actionManager !== this) {
  48353. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48354. return null;
  48355. }
  48356. }
  48357. this.actions.push(action);
  48358. if (ActionManager.Triggers[action.trigger]) {
  48359. ActionManager.Triggers[action.trigger]++;
  48360. }
  48361. else {
  48362. ActionManager.Triggers[action.trigger] = 1;
  48363. }
  48364. action._actionManager = this;
  48365. action._prepare();
  48366. return action;
  48367. };
  48368. /**
  48369. * Unregisters an action to this action manager
  48370. * @param action The action to be unregistered
  48371. * @return whether the action has been unregistered
  48372. */
  48373. ActionManager.prototype.unregisterAction = function (action) {
  48374. var index = this.actions.indexOf(action);
  48375. if (index !== -1) {
  48376. this.actions.splice(index, 1);
  48377. ActionManager.Triggers[action.trigger] -= 1;
  48378. if (ActionManager.Triggers[action.trigger] === 0) {
  48379. delete ActionManager.Triggers[action.trigger];
  48380. }
  48381. delete action._actionManager;
  48382. return true;
  48383. }
  48384. return false;
  48385. };
  48386. /**
  48387. * Process a specific trigger
  48388. * @param {number} trigger - the trigger to process
  48389. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48390. */
  48391. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48392. for (var index = 0; index < this.actions.length; index++) {
  48393. var action = this.actions[index];
  48394. if (action.trigger === trigger) {
  48395. if (evt) {
  48396. if (trigger === ActionManager.OnKeyUpTrigger
  48397. || trigger === ActionManager.OnKeyDownTrigger) {
  48398. var parameter = action.getTriggerParameter();
  48399. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48400. if (!parameter.toLowerCase) {
  48401. continue;
  48402. }
  48403. var lowerCase = parameter.toLowerCase();
  48404. if (lowerCase !== evt.sourceEvent.key) {
  48405. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48406. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48407. if (actualkey !== lowerCase) {
  48408. continue;
  48409. }
  48410. }
  48411. }
  48412. }
  48413. }
  48414. action._executeCurrent(evt);
  48415. }
  48416. }
  48417. };
  48418. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48419. var properties = propertyPath.split(".");
  48420. for (var index = 0; index < properties.length - 1; index++) {
  48421. target = target[properties[index]];
  48422. }
  48423. return target;
  48424. };
  48425. ActionManager.prototype._getProperty = function (propertyPath) {
  48426. var properties = propertyPath.split(".");
  48427. return properties[properties.length - 1];
  48428. };
  48429. ActionManager.prototype.serialize = function (name) {
  48430. var root = {
  48431. children: new Array(),
  48432. name: name,
  48433. type: 3,
  48434. properties: new Array() // Empty for root but required
  48435. };
  48436. for (var i = 0; i < this.actions.length; i++) {
  48437. var triggerObject = {
  48438. type: 0,
  48439. children: new Array(),
  48440. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48441. properties: new Array()
  48442. };
  48443. var triggerOptions = this.actions[i].triggerOptions;
  48444. if (triggerOptions && typeof triggerOptions !== "number") {
  48445. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48446. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48447. }
  48448. else {
  48449. var parameter = {};
  48450. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48451. if (triggerOptions.parameter.mesh) {
  48452. parameter._meshId = triggerOptions.parameter.mesh.id;
  48453. }
  48454. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48455. }
  48456. }
  48457. // Serialize child action, recursively
  48458. this.actions[i].serialize(triggerObject);
  48459. // Add serialized trigger
  48460. root.children.push(triggerObject);
  48461. }
  48462. return root;
  48463. };
  48464. ActionManager.Parse = function (parsedActions, object, scene) {
  48465. var actionManager = new ActionManager(scene);
  48466. if (object === null)
  48467. scene.actionManager = actionManager;
  48468. else
  48469. object.actionManager = actionManager;
  48470. // instanciate a new object
  48471. var instanciate = function (name, params) {
  48472. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48473. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48474. newInstance.constructor.apply(newInstance, params);
  48475. return newInstance;
  48476. };
  48477. var parseParameter = function (name, value, target, propertyPath) {
  48478. if (propertyPath === null) {
  48479. // String, boolean or float
  48480. var floatValue = parseFloat(value);
  48481. if (value === "true" || value === "false")
  48482. return value === "true";
  48483. else
  48484. return isNaN(floatValue) ? value : floatValue;
  48485. }
  48486. var effectiveTarget = propertyPath.split(".");
  48487. var values = value.split(",");
  48488. // Get effective Target
  48489. for (var i = 0; i < effectiveTarget.length; i++) {
  48490. target = target[effectiveTarget[i]];
  48491. }
  48492. // Return appropriate value with its type
  48493. if (typeof (target) === "boolean")
  48494. return values[0] === "true";
  48495. if (typeof (target) === "string")
  48496. return values[0];
  48497. // Parameters with multiple values such as Vector3 etc.
  48498. var split = new Array();
  48499. for (var i = 0; i < values.length; i++)
  48500. split.push(parseFloat(values[i]));
  48501. if (target instanceof BABYLON.Vector3)
  48502. return BABYLON.Vector3.FromArray(split);
  48503. if (target instanceof BABYLON.Vector4)
  48504. return BABYLON.Vector4.FromArray(split);
  48505. if (target instanceof BABYLON.Color3)
  48506. return BABYLON.Color3.FromArray(split);
  48507. if (target instanceof BABYLON.Color4)
  48508. return BABYLON.Color4.FromArray(split);
  48509. return parseFloat(values[0]);
  48510. };
  48511. // traverse graph per trigger
  48512. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48513. if (combineArray === void 0) { combineArray = null; }
  48514. if (parsedAction.detached)
  48515. return;
  48516. var parameters = new Array();
  48517. var target = null;
  48518. var propertyPath = null;
  48519. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48520. // Parameters
  48521. if (parsedAction.type === 2)
  48522. parameters.push(actionManager);
  48523. else
  48524. parameters.push(trigger);
  48525. if (combine) {
  48526. var actions = new Array();
  48527. for (var j = 0; j < parsedAction.combine.length; j++) {
  48528. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48529. }
  48530. parameters.push(actions);
  48531. }
  48532. else {
  48533. for (var i = 0; i < parsedAction.properties.length; i++) {
  48534. var value = parsedAction.properties[i].value;
  48535. var name = parsedAction.properties[i].name;
  48536. var targetType = parsedAction.properties[i].targetType;
  48537. if (name === "target")
  48538. if (targetType !== null && targetType === "SceneProperties")
  48539. value = target = scene;
  48540. else
  48541. value = target = scene.getNodeByName(value);
  48542. else if (name === "parent")
  48543. value = scene.getNodeByName(value);
  48544. else if (name === "sound")
  48545. value = scene.getSoundByName(value);
  48546. else if (name !== "propertyPath") {
  48547. if (parsedAction.type === 2 && name === "operator")
  48548. value = BABYLON.ValueCondition[value];
  48549. else
  48550. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48551. }
  48552. else {
  48553. propertyPath = value;
  48554. }
  48555. parameters.push(value);
  48556. }
  48557. }
  48558. if (combineArray === null) {
  48559. parameters.push(condition);
  48560. }
  48561. else {
  48562. parameters.push(null);
  48563. }
  48564. // If interpolate value action
  48565. if (parsedAction.name === "InterpolateValueAction") {
  48566. var param = parameters[parameters.length - 2];
  48567. parameters[parameters.length - 1] = param;
  48568. parameters[parameters.length - 2] = condition;
  48569. }
  48570. // Action or condition(s) and not CombineAction
  48571. var newAction = instanciate(parsedAction.name, parameters);
  48572. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48573. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48574. if (action)
  48575. action.then(nothing);
  48576. else
  48577. actionManager.registerAction(nothing);
  48578. action = nothing;
  48579. }
  48580. if (combineArray === null) {
  48581. if (newAction instanceof BABYLON.Condition) {
  48582. condition = newAction;
  48583. newAction = action;
  48584. }
  48585. else {
  48586. condition = null;
  48587. if (action)
  48588. action.then(newAction);
  48589. else
  48590. actionManager.registerAction(newAction);
  48591. }
  48592. }
  48593. else {
  48594. combineArray.push(newAction);
  48595. }
  48596. for (var i = 0; i < parsedAction.children.length; i++)
  48597. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48598. };
  48599. // triggers
  48600. for (var i = 0; i < parsedActions.children.length; i++) {
  48601. var triggerParams;
  48602. var trigger = parsedActions.children[i];
  48603. if (trigger.properties.length > 0) {
  48604. var param = trigger.properties[0].value;
  48605. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48606. if (value._meshId) {
  48607. value.mesh = scene.getMeshByID(value._meshId);
  48608. }
  48609. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48610. }
  48611. else
  48612. triggerParams = ActionManager[trigger.name];
  48613. for (var j = 0; j < trigger.children.length; j++) {
  48614. if (!trigger.detached)
  48615. traverse(trigger.children[j], triggerParams, null, null);
  48616. }
  48617. }
  48618. };
  48619. ActionManager.GetTriggerName = function (trigger) {
  48620. switch (trigger) {
  48621. case 0: return "NothingTrigger";
  48622. case 1: return "OnPickTrigger";
  48623. case 2: return "OnLeftPickTrigger";
  48624. case 3: return "OnRightPickTrigger";
  48625. case 4: return "OnCenterPickTrigger";
  48626. case 5: return "OnPickDownTrigger";
  48627. case 6: return "OnPickUpTrigger";
  48628. case 7: return "OnLongPressTrigger";
  48629. case 8: return "OnPointerOverTrigger";
  48630. case 9: return "OnPointerOutTrigger";
  48631. case 10: return "OnEveryFrameTrigger";
  48632. case 11: return "OnIntersectionEnterTrigger";
  48633. case 12: return "OnIntersectionExitTrigger";
  48634. case 13: return "OnKeyDownTrigger";
  48635. case 14: return "OnKeyUpTrigger";
  48636. case 15: return "OnPickOutTrigger";
  48637. default: return "";
  48638. }
  48639. };
  48640. // Statics
  48641. ActionManager._NothingTrigger = 0;
  48642. ActionManager._OnPickTrigger = 1;
  48643. ActionManager._OnLeftPickTrigger = 2;
  48644. ActionManager._OnRightPickTrigger = 3;
  48645. ActionManager._OnCenterPickTrigger = 4;
  48646. ActionManager._OnPickDownTrigger = 5;
  48647. ActionManager._OnDoublePickTrigger = 6;
  48648. ActionManager._OnPickUpTrigger = 7;
  48649. ActionManager._OnLongPressTrigger = 8;
  48650. ActionManager._OnPointerOverTrigger = 9;
  48651. ActionManager._OnPointerOutTrigger = 10;
  48652. ActionManager._OnEveryFrameTrigger = 11;
  48653. ActionManager._OnIntersectionEnterTrigger = 12;
  48654. ActionManager._OnIntersectionExitTrigger = 13;
  48655. ActionManager._OnKeyDownTrigger = 14;
  48656. ActionManager._OnKeyUpTrigger = 15;
  48657. ActionManager._OnPickOutTrigger = 16;
  48658. ActionManager.Triggers = {};
  48659. return ActionManager;
  48660. }());
  48661. BABYLON.ActionManager = ActionManager;
  48662. })(BABYLON || (BABYLON = {}));
  48663. //# sourceMappingURL=babylon.actionManager.js.map
  48664. var BABYLON;
  48665. (function (BABYLON) {
  48666. var InterpolateValueAction = /** @class */ (function (_super) {
  48667. __extends(InterpolateValueAction, _super);
  48668. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48669. if (duration === void 0) { duration = 1000; }
  48670. var _this = _super.call(this, triggerOptions, condition) || this;
  48671. _this.propertyPath = propertyPath;
  48672. _this.value = value;
  48673. _this.duration = duration;
  48674. _this.stopOtherAnimations = stopOtherAnimations;
  48675. _this.onInterpolationDone = onInterpolationDone;
  48676. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48677. _this._target = _this._effectiveTarget = target;
  48678. return _this;
  48679. }
  48680. InterpolateValueAction.prototype._prepare = function () {
  48681. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48682. this._property = this._getProperty(this.propertyPath);
  48683. };
  48684. InterpolateValueAction.prototype.execute = function () {
  48685. var _this = this;
  48686. var scene = this._actionManager.getScene();
  48687. var keys = [
  48688. {
  48689. frame: 0,
  48690. value: this._effectiveTarget[this._property]
  48691. }, {
  48692. frame: 100,
  48693. value: this.value
  48694. }
  48695. ];
  48696. var dataType;
  48697. if (typeof this.value === "number") {
  48698. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48699. }
  48700. else if (this.value instanceof BABYLON.Color3) {
  48701. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48702. }
  48703. else if (this.value instanceof BABYLON.Vector3) {
  48704. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48705. }
  48706. else if (this.value instanceof BABYLON.Matrix) {
  48707. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48708. }
  48709. else if (this.value instanceof BABYLON.Quaternion) {
  48710. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48711. }
  48712. else {
  48713. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48714. return;
  48715. }
  48716. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48717. animation.setKeys(keys);
  48718. if (this.stopOtherAnimations) {
  48719. scene.stopAnimation(this._effectiveTarget);
  48720. }
  48721. var wrapper = function () {
  48722. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48723. if (_this.onInterpolationDone) {
  48724. _this.onInterpolationDone();
  48725. }
  48726. };
  48727. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48728. };
  48729. InterpolateValueAction.prototype.serialize = function (parent) {
  48730. return _super.prototype._serialize.call(this, {
  48731. name: "InterpolateValueAction",
  48732. properties: [
  48733. BABYLON.Action._GetTargetProperty(this._target),
  48734. { name: "propertyPath", value: this.propertyPath },
  48735. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48736. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48737. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48738. ]
  48739. }, parent);
  48740. };
  48741. return InterpolateValueAction;
  48742. }(BABYLON.Action));
  48743. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48744. })(BABYLON || (BABYLON = {}));
  48745. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48746. var BABYLON;
  48747. (function (BABYLON) {
  48748. var SwitchBooleanAction = /** @class */ (function (_super) {
  48749. __extends(SwitchBooleanAction, _super);
  48750. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48751. var _this = _super.call(this, triggerOptions, condition) || this;
  48752. _this.propertyPath = propertyPath;
  48753. _this._target = _this._effectiveTarget = target;
  48754. return _this;
  48755. }
  48756. SwitchBooleanAction.prototype._prepare = function () {
  48757. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48758. this._property = this._getProperty(this.propertyPath);
  48759. };
  48760. SwitchBooleanAction.prototype.execute = function () {
  48761. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48762. };
  48763. SwitchBooleanAction.prototype.serialize = function (parent) {
  48764. return _super.prototype._serialize.call(this, {
  48765. name: "SwitchBooleanAction",
  48766. properties: [
  48767. BABYLON.Action._GetTargetProperty(this._target),
  48768. { name: "propertyPath", value: this.propertyPath }
  48769. ]
  48770. }, parent);
  48771. };
  48772. return SwitchBooleanAction;
  48773. }(BABYLON.Action));
  48774. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48775. var SetStateAction = /** @class */ (function (_super) {
  48776. __extends(SetStateAction, _super);
  48777. function SetStateAction(triggerOptions, target, value, condition) {
  48778. var _this = _super.call(this, triggerOptions, condition) || this;
  48779. _this.value = value;
  48780. _this._target = target;
  48781. return _this;
  48782. }
  48783. SetStateAction.prototype.execute = function () {
  48784. this._target.state = this.value;
  48785. };
  48786. SetStateAction.prototype.serialize = function (parent) {
  48787. return _super.prototype._serialize.call(this, {
  48788. name: "SetStateAction",
  48789. properties: [
  48790. BABYLON.Action._GetTargetProperty(this._target),
  48791. { name: "value", value: this.value }
  48792. ]
  48793. }, parent);
  48794. };
  48795. return SetStateAction;
  48796. }(BABYLON.Action));
  48797. BABYLON.SetStateAction = SetStateAction;
  48798. var SetValueAction = /** @class */ (function (_super) {
  48799. __extends(SetValueAction, _super);
  48800. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48801. var _this = _super.call(this, triggerOptions, condition) || this;
  48802. _this.propertyPath = propertyPath;
  48803. _this.value = value;
  48804. _this._target = _this._effectiveTarget = target;
  48805. return _this;
  48806. }
  48807. SetValueAction.prototype._prepare = function () {
  48808. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48809. this._property = this._getProperty(this.propertyPath);
  48810. };
  48811. SetValueAction.prototype.execute = function () {
  48812. this._effectiveTarget[this._property] = this.value;
  48813. if (this._target.markAsDirty) {
  48814. this._target.markAsDirty(this._property);
  48815. }
  48816. };
  48817. SetValueAction.prototype.serialize = function (parent) {
  48818. return _super.prototype._serialize.call(this, {
  48819. name: "SetValueAction",
  48820. properties: [
  48821. BABYLON.Action._GetTargetProperty(this._target),
  48822. { name: "propertyPath", value: this.propertyPath },
  48823. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48824. ]
  48825. }, parent);
  48826. };
  48827. return SetValueAction;
  48828. }(BABYLON.Action));
  48829. BABYLON.SetValueAction = SetValueAction;
  48830. var IncrementValueAction = /** @class */ (function (_super) {
  48831. __extends(IncrementValueAction, _super);
  48832. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48833. var _this = _super.call(this, triggerOptions, condition) || this;
  48834. _this.propertyPath = propertyPath;
  48835. _this.value = value;
  48836. _this._target = _this._effectiveTarget = target;
  48837. return _this;
  48838. }
  48839. IncrementValueAction.prototype._prepare = function () {
  48840. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48841. this._property = this._getProperty(this.propertyPath);
  48842. if (typeof this._effectiveTarget[this._property] !== "number") {
  48843. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48844. }
  48845. };
  48846. IncrementValueAction.prototype.execute = function () {
  48847. this._effectiveTarget[this._property] += this.value;
  48848. if (this._target.markAsDirty) {
  48849. this._target.markAsDirty(this._property);
  48850. }
  48851. };
  48852. IncrementValueAction.prototype.serialize = function (parent) {
  48853. return _super.prototype._serialize.call(this, {
  48854. name: "IncrementValueAction",
  48855. properties: [
  48856. BABYLON.Action._GetTargetProperty(this._target),
  48857. { name: "propertyPath", value: this.propertyPath },
  48858. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48859. ]
  48860. }, parent);
  48861. };
  48862. return IncrementValueAction;
  48863. }(BABYLON.Action));
  48864. BABYLON.IncrementValueAction = IncrementValueAction;
  48865. var PlayAnimationAction = /** @class */ (function (_super) {
  48866. __extends(PlayAnimationAction, _super);
  48867. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48868. var _this = _super.call(this, triggerOptions, condition) || this;
  48869. _this.from = from;
  48870. _this.to = to;
  48871. _this.loop = loop;
  48872. _this._target = target;
  48873. return _this;
  48874. }
  48875. PlayAnimationAction.prototype._prepare = function () {
  48876. };
  48877. PlayAnimationAction.prototype.execute = function () {
  48878. var scene = this._actionManager.getScene();
  48879. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48880. };
  48881. PlayAnimationAction.prototype.serialize = function (parent) {
  48882. return _super.prototype._serialize.call(this, {
  48883. name: "PlayAnimationAction",
  48884. properties: [
  48885. BABYLON.Action._GetTargetProperty(this._target),
  48886. { name: "from", value: String(this.from) },
  48887. { name: "to", value: String(this.to) },
  48888. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48889. ]
  48890. }, parent);
  48891. };
  48892. return PlayAnimationAction;
  48893. }(BABYLON.Action));
  48894. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48895. var StopAnimationAction = /** @class */ (function (_super) {
  48896. __extends(StopAnimationAction, _super);
  48897. function StopAnimationAction(triggerOptions, target, condition) {
  48898. var _this = _super.call(this, triggerOptions, condition) || this;
  48899. _this._target = target;
  48900. return _this;
  48901. }
  48902. StopAnimationAction.prototype._prepare = function () {
  48903. };
  48904. StopAnimationAction.prototype.execute = function () {
  48905. var scene = this._actionManager.getScene();
  48906. scene.stopAnimation(this._target);
  48907. };
  48908. StopAnimationAction.prototype.serialize = function (parent) {
  48909. return _super.prototype._serialize.call(this, {
  48910. name: "StopAnimationAction",
  48911. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48912. }, parent);
  48913. };
  48914. return StopAnimationAction;
  48915. }(BABYLON.Action));
  48916. BABYLON.StopAnimationAction = StopAnimationAction;
  48917. var DoNothingAction = /** @class */ (function (_super) {
  48918. __extends(DoNothingAction, _super);
  48919. function DoNothingAction(triggerOptions, condition) {
  48920. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48921. return _super.call(this, triggerOptions, condition) || this;
  48922. }
  48923. DoNothingAction.prototype.execute = function () {
  48924. };
  48925. DoNothingAction.prototype.serialize = function (parent) {
  48926. return _super.prototype._serialize.call(this, {
  48927. name: "DoNothingAction",
  48928. properties: []
  48929. }, parent);
  48930. };
  48931. return DoNothingAction;
  48932. }(BABYLON.Action));
  48933. BABYLON.DoNothingAction = DoNothingAction;
  48934. var CombineAction = /** @class */ (function (_super) {
  48935. __extends(CombineAction, _super);
  48936. function CombineAction(triggerOptions, children, condition) {
  48937. var _this = _super.call(this, triggerOptions, condition) || this;
  48938. _this.children = children;
  48939. return _this;
  48940. }
  48941. CombineAction.prototype._prepare = function () {
  48942. for (var index = 0; index < this.children.length; index++) {
  48943. this.children[index]._actionManager = this._actionManager;
  48944. this.children[index]._prepare();
  48945. }
  48946. };
  48947. CombineAction.prototype.execute = function (evt) {
  48948. for (var index = 0; index < this.children.length; index++) {
  48949. this.children[index].execute(evt);
  48950. }
  48951. };
  48952. CombineAction.prototype.serialize = function (parent) {
  48953. var serializationObject = _super.prototype._serialize.call(this, {
  48954. name: "CombineAction",
  48955. properties: [],
  48956. combine: []
  48957. }, parent);
  48958. for (var i = 0; i < this.children.length; i++) {
  48959. serializationObject.combine.push(this.children[i].serialize(null));
  48960. }
  48961. return serializationObject;
  48962. };
  48963. return CombineAction;
  48964. }(BABYLON.Action));
  48965. BABYLON.CombineAction = CombineAction;
  48966. var ExecuteCodeAction = /** @class */ (function (_super) {
  48967. __extends(ExecuteCodeAction, _super);
  48968. function ExecuteCodeAction(triggerOptions, func, condition) {
  48969. var _this = _super.call(this, triggerOptions, condition) || this;
  48970. _this.func = func;
  48971. return _this;
  48972. }
  48973. ExecuteCodeAction.prototype.execute = function (evt) {
  48974. this.func(evt);
  48975. };
  48976. return ExecuteCodeAction;
  48977. }(BABYLON.Action));
  48978. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48979. var SetParentAction = /** @class */ (function (_super) {
  48980. __extends(SetParentAction, _super);
  48981. function SetParentAction(triggerOptions, target, parent, condition) {
  48982. var _this = _super.call(this, triggerOptions, condition) || this;
  48983. _this._target = target;
  48984. _this._parent = parent;
  48985. return _this;
  48986. }
  48987. SetParentAction.prototype._prepare = function () {
  48988. };
  48989. SetParentAction.prototype.execute = function () {
  48990. if (this._target.parent === this._parent) {
  48991. return;
  48992. }
  48993. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48994. invertParentWorldMatrix.invert();
  48995. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48996. this._target.parent = this._parent;
  48997. };
  48998. SetParentAction.prototype.serialize = function (parent) {
  48999. return _super.prototype._serialize.call(this, {
  49000. name: "SetParentAction",
  49001. properties: [
  49002. BABYLON.Action._GetTargetProperty(this._target),
  49003. BABYLON.Action._GetTargetProperty(this._parent),
  49004. ]
  49005. }, parent);
  49006. };
  49007. return SetParentAction;
  49008. }(BABYLON.Action));
  49009. BABYLON.SetParentAction = SetParentAction;
  49010. var PlaySoundAction = /** @class */ (function (_super) {
  49011. __extends(PlaySoundAction, _super);
  49012. function PlaySoundAction(triggerOptions, sound, condition) {
  49013. var _this = _super.call(this, triggerOptions, condition) || this;
  49014. _this._sound = sound;
  49015. return _this;
  49016. }
  49017. PlaySoundAction.prototype._prepare = function () {
  49018. };
  49019. PlaySoundAction.prototype.execute = function () {
  49020. if (this._sound !== undefined)
  49021. this._sound.play();
  49022. };
  49023. PlaySoundAction.prototype.serialize = function (parent) {
  49024. return _super.prototype._serialize.call(this, {
  49025. name: "PlaySoundAction",
  49026. properties: [{ name: "sound", value: this._sound.name }]
  49027. }, parent);
  49028. };
  49029. return PlaySoundAction;
  49030. }(BABYLON.Action));
  49031. BABYLON.PlaySoundAction = PlaySoundAction;
  49032. var StopSoundAction = /** @class */ (function (_super) {
  49033. __extends(StopSoundAction, _super);
  49034. function StopSoundAction(triggerOptions, sound, condition) {
  49035. var _this = _super.call(this, triggerOptions, condition) || this;
  49036. _this._sound = sound;
  49037. return _this;
  49038. }
  49039. StopSoundAction.prototype._prepare = function () {
  49040. };
  49041. StopSoundAction.prototype.execute = function () {
  49042. if (this._sound !== undefined)
  49043. this._sound.stop();
  49044. };
  49045. StopSoundAction.prototype.serialize = function (parent) {
  49046. return _super.prototype._serialize.call(this, {
  49047. name: "StopSoundAction",
  49048. properties: [{ name: "sound", value: this._sound.name }]
  49049. }, parent);
  49050. };
  49051. return StopSoundAction;
  49052. }(BABYLON.Action));
  49053. BABYLON.StopSoundAction = StopSoundAction;
  49054. })(BABYLON || (BABYLON = {}));
  49055. //# sourceMappingURL=babylon.directActions.js.map
  49056. var BABYLON;
  49057. (function (BABYLON) {
  49058. var SpriteManager = /** @class */ (function () {
  49059. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49060. if (epsilon === void 0) { epsilon = 0.01; }
  49061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49062. this.name = name;
  49063. this.sprites = new Array();
  49064. this.renderingGroupId = 0;
  49065. this.layerMask = 0x0FFFFFFF;
  49066. this.fogEnabled = true;
  49067. this.isPickable = false;
  49068. /**
  49069. * An event triggered when the manager is disposed.
  49070. * @type {BABYLON.Observable}
  49071. */
  49072. this.onDisposeObservable = new BABYLON.Observable();
  49073. this._vertexBuffers = {};
  49074. this._capacity = capacity;
  49075. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49076. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49077. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49078. if (cellSize.width && cellSize.height) {
  49079. this.cellWidth = cellSize.width;
  49080. this.cellHeight = cellSize.height;
  49081. }
  49082. else if (cellSize !== undefined) {
  49083. this.cellWidth = cellSize;
  49084. this.cellHeight = cellSize;
  49085. }
  49086. else {
  49087. return;
  49088. }
  49089. this._epsilon = epsilon;
  49090. this._scene = scene;
  49091. this._scene.spriteManagers.push(this);
  49092. var indices = [];
  49093. var index = 0;
  49094. for (var count = 0; count < capacity; count++) {
  49095. indices.push(index);
  49096. indices.push(index + 1);
  49097. indices.push(index + 2);
  49098. indices.push(index);
  49099. indices.push(index + 2);
  49100. indices.push(index + 3);
  49101. index += 4;
  49102. }
  49103. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49104. // VBO
  49105. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49106. this._vertexData = new Float32Array(capacity * 16 * 4);
  49107. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49108. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49109. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49110. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49111. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49112. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49113. this._vertexBuffers["options"] = options;
  49114. this._vertexBuffers["cellInfo"] = cellInfo;
  49115. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49116. // Effects
  49117. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49118. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49119. }
  49120. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49121. set: function (callback) {
  49122. if (this._onDisposeObserver) {
  49123. this.onDisposeObservable.remove(this._onDisposeObserver);
  49124. }
  49125. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49126. },
  49127. enumerable: true,
  49128. configurable: true
  49129. });
  49130. Object.defineProperty(SpriteManager.prototype, "texture", {
  49131. get: function () {
  49132. return this._spriteTexture;
  49133. },
  49134. set: function (value) {
  49135. this._spriteTexture = value;
  49136. },
  49137. enumerable: true,
  49138. configurable: true
  49139. });
  49140. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49141. var arrayOffset = index * 16;
  49142. if (offsetX === 0)
  49143. offsetX = this._epsilon;
  49144. else if (offsetX === 1)
  49145. offsetX = 1 - this._epsilon;
  49146. if (offsetY === 0)
  49147. offsetY = this._epsilon;
  49148. else if (offsetY === 1)
  49149. offsetY = 1 - this._epsilon;
  49150. this._vertexData[arrayOffset] = sprite.position.x;
  49151. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49152. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49153. this._vertexData[arrayOffset + 3] = sprite.angle;
  49154. this._vertexData[arrayOffset + 4] = sprite.width;
  49155. this._vertexData[arrayOffset + 5] = sprite.height;
  49156. this._vertexData[arrayOffset + 6] = offsetX;
  49157. this._vertexData[arrayOffset + 7] = offsetY;
  49158. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49159. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49160. var offset = (sprite.cellIndex / rowSize) >> 0;
  49161. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49162. this._vertexData[arrayOffset + 11] = offset;
  49163. // Color
  49164. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49165. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49166. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49167. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49168. };
  49169. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49170. var count = Math.min(this._capacity, this.sprites.length);
  49171. var min = BABYLON.Vector3.Zero();
  49172. var max = BABYLON.Vector3.Zero();
  49173. var distance = Number.MAX_VALUE;
  49174. var currentSprite = null;
  49175. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49176. var cameraView = camera.getViewMatrix();
  49177. for (var index = 0; index < count; index++) {
  49178. var sprite = this.sprites[index];
  49179. if (!sprite) {
  49180. continue;
  49181. }
  49182. if (predicate) {
  49183. if (!predicate(sprite)) {
  49184. continue;
  49185. }
  49186. }
  49187. else if (!sprite.isPickable) {
  49188. continue;
  49189. }
  49190. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49191. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49192. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49193. if (ray.intersectsBoxMinMax(min, max)) {
  49194. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49195. if (distance > currentDistance) {
  49196. distance = currentDistance;
  49197. currentSprite = sprite;
  49198. if (fastCheck) {
  49199. break;
  49200. }
  49201. }
  49202. }
  49203. }
  49204. if (currentSprite) {
  49205. var result = new BABYLON.PickingInfo();
  49206. result.hit = true;
  49207. result.pickedSprite = currentSprite;
  49208. result.distance = distance;
  49209. return result;
  49210. }
  49211. return null;
  49212. };
  49213. SpriteManager.prototype.render = function () {
  49214. // Check
  49215. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49216. return;
  49217. var engine = this._scene.getEngine();
  49218. var baseSize = this._spriteTexture.getBaseSize();
  49219. // Sprites
  49220. var deltaTime = engine.getDeltaTime();
  49221. var max = Math.min(this._capacity, this.sprites.length);
  49222. var rowSize = baseSize.width / this.cellWidth;
  49223. var offset = 0;
  49224. for (var index = 0; index < max; index++) {
  49225. var sprite = this.sprites[index];
  49226. if (!sprite) {
  49227. continue;
  49228. }
  49229. sprite._animate(deltaTime);
  49230. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49231. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49232. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49233. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49234. }
  49235. this._buffer.update(this._vertexData);
  49236. // Render
  49237. var effect = this._effectBase;
  49238. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49239. effect = this._effectFog;
  49240. }
  49241. engine.enableEffect(effect);
  49242. var viewMatrix = this._scene.getViewMatrix();
  49243. effect.setTexture("diffuseSampler", this._spriteTexture);
  49244. effect.setMatrix("view", viewMatrix);
  49245. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49246. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49247. // Fog
  49248. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49249. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49250. effect.setColor3("vFogColor", this._scene.fogColor);
  49251. }
  49252. // VBOs
  49253. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49254. // Draw order
  49255. engine.setDepthFunctionToLessOrEqual();
  49256. effect.setBool("alphaTest", true);
  49257. engine.setColorWrite(false);
  49258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49259. engine.setColorWrite(true);
  49260. effect.setBool("alphaTest", false);
  49261. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49262. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49263. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49264. };
  49265. SpriteManager.prototype.dispose = function () {
  49266. if (this._buffer) {
  49267. this._buffer.dispose();
  49268. this._buffer = null;
  49269. }
  49270. if (this._indexBuffer) {
  49271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49272. this._indexBuffer = null;
  49273. }
  49274. if (this._spriteTexture) {
  49275. this._spriteTexture.dispose();
  49276. this._spriteTexture = null;
  49277. }
  49278. // Remove from scene
  49279. var index = this._scene.spriteManagers.indexOf(this);
  49280. this._scene.spriteManagers.splice(index, 1);
  49281. // Callback
  49282. this.onDisposeObservable.notifyObservers(this);
  49283. this.onDisposeObservable.clear();
  49284. };
  49285. return SpriteManager;
  49286. }());
  49287. BABYLON.SpriteManager = SpriteManager;
  49288. })(BABYLON || (BABYLON = {}));
  49289. //# sourceMappingURL=babylon.spriteManager.js.map
  49290. var BABYLON;
  49291. (function (BABYLON) {
  49292. var Sprite = /** @class */ (function () {
  49293. function Sprite(name, manager) {
  49294. this.name = name;
  49295. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49296. this.width = 1.0;
  49297. this.height = 1.0;
  49298. this.angle = 0;
  49299. this.cellIndex = 0;
  49300. this.invertU = 0;
  49301. this.invertV = 0;
  49302. this.animations = new Array();
  49303. this.isPickable = false;
  49304. this._animationStarted = false;
  49305. this._loopAnimation = false;
  49306. this._fromIndex = 0;
  49307. this._toIndex = 0;
  49308. this._delay = 0;
  49309. this._direction = 1;
  49310. this._time = 0;
  49311. this._manager = manager;
  49312. this._manager.sprites.push(this);
  49313. this.position = BABYLON.Vector3.Zero();
  49314. }
  49315. Object.defineProperty(Sprite.prototype, "size", {
  49316. get: function () {
  49317. return this.width;
  49318. },
  49319. set: function (value) {
  49320. this.width = value;
  49321. this.height = value;
  49322. },
  49323. enumerable: true,
  49324. configurable: true
  49325. });
  49326. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49327. this._fromIndex = from;
  49328. this._toIndex = to;
  49329. this._loopAnimation = loop;
  49330. this._delay = delay;
  49331. this._animationStarted = true;
  49332. this._direction = from < to ? 1 : -1;
  49333. this.cellIndex = from;
  49334. this._time = 0;
  49335. this._onAnimationEnd = onAnimationEnd;
  49336. };
  49337. Sprite.prototype.stopAnimation = function () {
  49338. this._animationStarted = false;
  49339. };
  49340. Sprite.prototype._animate = function (deltaTime) {
  49341. if (!this._animationStarted)
  49342. return;
  49343. this._time += deltaTime;
  49344. if (this._time > this._delay) {
  49345. this._time = this._time % this._delay;
  49346. this.cellIndex += this._direction;
  49347. if (this.cellIndex > this._toIndex) {
  49348. if (this._loopAnimation) {
  49349. this.cellIndex = this._fromIndex;
  49350. }
  49351. else {
  49352. this.cellIndex = this._toIndex;
  49353. this._animationStarted = false;
  49354. if (this._onAnimationEnd) {
  49355. this._onAnimationEnd();
  49356. }
  49357. if (this.disposeWhenFinishedAnimating) {
  49358. this.dispose();
  49359. }
  49360. }
  49361. }
  49362. }
  49363. };
  49364. Sprite.prototype.dispose = function () {
  49365. for (var i = 0; i < this._manager.sprites.length; i++) {
  49366. if (this._manager.sprites[i] == this) {
  49367. this._manager.sprites.splice(i, 1);
  49368. }
  49369. }
  49370. };
  49371. return Sprite;
  49372. }());
  49373. BABYLON.Sprite = Sprite;
  49374. })(BABYLON || (BABYLON = {}));
  49375. //# sourceMappingURL=babylon.sprite.js.map
  49376. var BABYLON;
  49377. (function (BABYLON) {
  49378. var IntersectionInfo = /** @class */ (function () {
  49379. function IntersectionInfo(bu, bv, distance) {
  49380. this.bu = bu;
  49381. this.bv = bv;
  49382. this.distance = distance;
  49383. this.faceId = 0;
  49384. this.subMeshId = 0;
  49385. }
  49386. return IntersectionInfo;
  49387. }());
  49388. BABYLON.IntersectionInfo = IntersectionInfo;
  49389. var PickingInfo = /** @class */ (function () {
  49390. function PickingInfo() {
  49391. this.hit = false;
  49392. this.distance = 0;
  49393. this.pickedPoint = null;
  49394. this.pickedMesh = null;
  49395. this.bu = 0;
  49396. this.bv = 0;
  49397. this.faceId = -1;
  49398. this.subMeshId = 0;
  49399. this.pickedSprite = null;
  49400. }
  49401. // Methods
  49402. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49403. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49404. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49405. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49406. return null;
  49407. }
  49408. var indices = this.pickedMesh.getIndices();
  49409. if (!indices) {
  49410. return null;
  49411. }
  49412. var result;
  49413. if (useVerticesNormals) {
  49414. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49415. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49416. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49417. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49418. normal0 = normal0.scale(this.bu);
  49419. normal1 = normal1.scale(this.bv);
  49420. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49421. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49422. }
  49423. else {
  49424. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49425. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49426. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49427. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49428. var p1p2 = vertex1.subtract(vertex2);
  49429. var p3p2 = vertex3.subtract(vertex2);
  49430. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49431. }
  49432. if (useWorldCoordinates) {
  49433. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49434. }
  49435. return BABYLON.Vector3.Normalize(result);
  49436. };
  49437. PickingInfo.prototype.getTextureCoordinates = function () {
  49438. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49439. return null;
  49440. }
  49441. var indices = this.pickedMesh.getIndices();
  49442. if (!indices) {
  49443. return null;
  49444. }
  49445. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49446. if (!uvs) {
  49447. return null;
  49448. }
  49449. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49450. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49451. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49452. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49453. uv1 = uv1.scale(this.bu);
  49454. uv2 = uv2.scale(this.bv);
  49455. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49456. };
  49457. return PickingInfo;
  49458. }());
  49459. BABYLON.PickingInfo = PickingInfo;
  49460. })(BABYLON || (BABYLON = {}));
  49461. //# sourceMappingURL=babylon.pickingInfo.js.map
  49462. var BABYLON;
  49463. (function (BABYLON) {
  49464. var Ray = /** @class */ (function () {
  49465. function Ray(origin, direction, length) {
  49466. if (length === void 0) { length = Number.MAX_VALUE; }
  49467. this.origin = origin;
  49468. this.direction = direction;
  49469. this.length = length;
  49470. }
  49471. // Methods
  49472. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49473. var d = 0.0;
  49474. var maxValue = Number.MAX_VALUE;
  49475. var inv;
  49476. var min;
  49477. var max;
  49478. var temp;
  49479. if (Math.abs(this.direction.x) < 0.0000001) {
  49480. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49481. return false;
  49482. }
  49483. }
  49484. else {
  49485. inv = 1.0 / this.direction.x;
  49486. min = (minimum.x - this.origin.x) * inv;
  49487. max = (maximum.x - this.origin.x) * inv;
  49488. if (max === -Infinity) {
  49489. max = Infinity;
  49490. }
  49491. if (min > max) {
  49492. temp = min;
  49493. min = max;
  49494. max = temp;
  49495. }
  49496. d = Math.max(min, d);
  49497. maxValue = Math.min(max, maxValue);
  49498. if (d > maxValue) {
  49499. return false;
  49500. }
  49501. }
  49502. if (Math.abs(this.direction.y) < 0.0000001) {
  49503. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49504. return false;
  49505. }
  49506. }
  49507. else {
  49508. inv = 1.0 / this.direction.y;
  49509. min = (minimum.y - this.origin.y) * inv;
  49510. max = (maximum.y - this.origin.y) * inv;
  49511. if (max === -Infinity) {
  49512. max = Infinity;
  49513. }
  49514. if (min > max) {
  49515. temp = min;
  49516. min = max;
  49517. max = temp;
  49518. }
  49519. d = Math.max(min, d);
  49520. maxValue = Math.min(max, maxValue);
  49521. if (d > maxValue) {
  49522. return false;
  49523. }
  49524. }
  49525. if (Math.abs(this.direction.z) < 0.0000001) {
  49526. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49527. return false;
  49528. }
  49529. }
  49530. else {
  49531. inv = 1.0 / this.direction.z;
  49532. min = (minimum.z - this.origin.z) * inv;
  49533. max = (maximum.z - this.origin.z) * inv;
  49534. if (max === -Infinity) {
  49535. max = Infinity;
  49536. }
  49537. if (min > max) {
  49538. temp = min;
  49539. min = max;
  49540. max = temp;
  49541. }
  49542. d = Math.max(min, d);
  49543. maxValue = Math.min(max, maxValue);
  49544. if (d > maxValue) {
  49545. return false;
  49546. }
  49547. }
  49548. return true;
  49549. };
  49550. Ray.prototype.intersectsBox = function (box) {
  49551. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49552. };
  49553. Ray.prototype.intersectsSphere = function (sphere) {
  49554. var x = sphere.center.x - this.origin.x;
  49555. var y = sphere.center.y - this.origin.y;
  49556. var z = sphere.center.z - this.origin.z;
  49557. var pyth = (x * x) + (y * y) + (z * z);
  49558. var rr = sphere.radius * sphere.radius;
  49559. if (pyth <= rr) {
  49560. return true;
  49561. }
  49562. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49563. if (dot < 0.0) {
  49564. return false;
  49565. }
  49566. var temp = pyth - (dot * dot);
  49567. return temp <= rr;
  49568. };
  49569. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49570. if (!this._edge1) {
  49571. this._edge1 = BABYLON.Vector3.Zero();
  49572. this._edge2 = BABYLON.Vector3.Zero();
  49573. this._pvec = BABYLON.Vector3.Zero();
  49574. this._tvec = BABYLON.Vector3.Zero();
  49575. this._qvec = BABYLON.Vector3.Zero();
  49576. }
  49577. vertex1.subtractToRef(vertex0, this._edge1);
  49578. vertex2.subtractToRef(vertex0, this._edge2);
  49579. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49580. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49581. if (det === 0) {
  49582. return null;
  49583. }
  49584. var invdet = 1 / det;
  49585. this.origin.subtractToRef(vertex0, this._tvec);
  49586. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49587. if (bu < 0 || bu > 1.0) {
  49588. return null;
  49589. }
  49590. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49591. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49592. if (bv < 0 || bu + bv > 1.0) {
  49593. return null;
  49594. }
  49595. //check if the distance is longer than the predefined length.
  49596. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49597. if (distance > this.length) {
  49598. return null;
  49599. }
  49600. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49601. };
  49602. Ray.prototype.intersectsPlane = function (plane) {
  49603. var distance;
  49604. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49605. if (Math.abs(result1) < 9.99999997475243E-07) {
  49606. return null;
  49607. }
  49608. else {
  49609. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49610. distance = (-plane.d - result2) / result1;
  49611. if (distance < 0.0) {
  49612. if (distance < -9.99999997475243E-07) {
  49613. return null;
  49614. }
  49615. else {
  49616. return 0;
  49617. }
  49618. }
  49619. return distance;
  49620. }
  49621. };
  49622. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49623. var tm = BABYLON.Tmp.Matrix[0];
  49624. mesh.getWorldMatrix().invertToRef(tm);
  49625. if (this._tmpRay) {
  49626. Ray.TransformToRef(this, tm, this._tmpRay);
  49627. }
  49628. else {
  49629. this._tmpRay = Ray.Transform(this, tm);
  49630. }
  49631. return mesh.intersects(this._tmpRay, fastCheck);
  49632. };
  49633. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49634. if (results) {
  49635. results.length = 0;
  49636. }
  49637. else {
  49638. results = [];
  49639. }
  49640. for (var i = 0; i < meshes.length; i++) {
  49641. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49642. if (pickInfo.hit) {
  49643. results.push(pickInfo);
  49644. }
  49645. }
  49646. results.sort(this._comparePickingInfo);
  49647. return results;
  49648. };
  49649. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49650. if (pickingInfoA.distance < pickingInfoB.distance) {
  49651. return -1;
  49652. }
  49653. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49654. return 1;
  49655. }
  49656. else {
  49657. return 0;
  49658. }
  49659. };
  49660. /**
  49661. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49662. * @param sega the first point of the segment to test the intersection against
  49663. * @param segb the second point of the segment to test the intersection against
  49664. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49665. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49666. */
  49667. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49668. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49669. var u = segb.subtract(sega);
  49670. var v = rsegb.subtract(this.origin);
  49671. var w = sega.subtract(this.origin);
  49672. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49673. var b = BABYLON.Vector3.Dot(u, v);
  49674. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49675. var d = BABYLON.Vector3.Dot(u, w);
  49676. var e = BABYLON.Vector3.Dot(v, w);
  49677. var D = a * c - b * b; // always >= 0
  49678. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49679. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49680. // compute the line parameters of the two closest points
  49681. if (D < Ray.smallnum) {
  49682. sN = 0.0; // force using point P0 on segment S1
  49683. sD = 1.0; // to prevent possible division by 0.0 later
  49684. tN = e;
  49685. tD = c;
  49686. }
  49687. else {
  49688. sN = (b * e - c * d);
  49689. tN = (a * e - b * d);
  49690. if (sN < 0.0) {
  49691. sN = 0.0;
  49692. tN = e;
  49693. tD = c;
  49694. }
  49695. else if (sN > sD) {
  49696. sN = sD;
  49697. tN = e + b;
  49698. tD = c;
  49699. }
  49700. }
  49701. if (tN < 0.0) {
  49702. tN = 0.0;
  49703. // recompute sc for this edge
  49704. if (-d < 0.0) {
  49705. sN = 0.0;
  49706. }
  49707. else if (-d > a)
  49708. sN = sD;
  49709. else {
  49710. sN = -d;
  49711. sD = a;
  49712. }
  49713. }
  49714. else if (tN > tD) {
  49715. tN = tD;
  49716. // recompute sc for this edge
  49717. if ((-d + b) < 0.0) {
  49718. sN = 0;
  49719. }
  49720. else if ((-d + b) > a) {
  49721. sN = sD;
  49722. }
  49723. else {
  49724. sN = (-d + b);
  49725. sD = a;
  49726. }
  49727. }
  49728. // finally do the division to get sc and tc
  49729. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49730. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49731. // get the difference of the two closest points
  49732. var qtc = v.multiplyByFloats(tc, tc, tc);
  49733. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49734. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49735. if (isIntersected) {
  49736. return qtc.length();
  49737. }
  49738. return -1;
  49739. };
  49740. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49741. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49742. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49743. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49744. this.direction.normalize();
  49745. return this;
  49746. };
  49747. // Statics
  49748. Ray.Zero = function () {
  49749. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49750. };
  49751. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49752. var result = Ray.Zero();
  49753. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49754. };
  49755. /**
  49756. * 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
  49757. * transformed to the given world matrix.
  49758. * @param origin The origin point
  49759. * @param end The end point
  49760. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49761. */
  49762. Ray.CreateNewFromTo = function (origin, end, world) {
  49763. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49764. var direction = end.subtract(origin);
  49765. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49766. direction.normalize();
  49767. return Ray.Transform(new Ray(origin, direction, length), world);
  49768. };
  49769. Ray.Transform = function (ray, matrix) {
  49770. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49771. Ray.TransformToRef(ray, matrix, result);
  49772. return result;
  49773. };
  49774. Ray.TransformToRef = function (ray, matrix, result) {
  49775. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49776. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49777. result.length = ray.length;
  49778. var dir = result.direction;
  49779. var len = dir.length();
  49780. if (!(len === 0 || len === 1)) {
  49781. var num = 1.0 / len;
  49782. dir.x *= num;
  49783. dir.y *= num;
  49784. dir.z *= num;
  49785. result.length *= len;
  49786. }
  49787. };
  49788. Ray.smallnum = 0.00000001;
  49789. Ray.rayl = 10e8;
  49790. return Ray;
  49791. }());
  49792. BABYLON.Ray = Ray;
  49793. })(BABYLON || (BABYLON = {}));
  49794. //# sourceMappingURL=babylon.ray.js.map
  49795. var BABYLON;
  49796. (function (BABYLON) {
  49797. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49798. if (boxMin.x > sphereCenter.x + sphereRadius)
  49799. return false;
  49800. if (sphereCenter.x - sphereRadius > boxMax.x)
  49801. return false;
  49802. if (boxMin.y > sphereCenter.y + sphereRadius)
  49803. return false;
  49804. if (sphereCenter.y - sphereRadius > boxMax.y)
  49805. return false;
  49806. if (boxMin.z > sphereCenter.z + sphereRadius)
  49807. return false;
  49808. if (sphereCenter.z - sphereRadius > boxMax.z)
  49809. return false;
  49810. return true;
  49811. };
  49812. var getLowestRoot = (function () {
  49813. var result = { root: 0, found: false };
  49814. return function (a, b, c, maxR) {
  49815. result.root = 0;
  49816. result.found = false;
  49817. var determinant = b * b - 4.0 * a * c;
  49818. if (determinant < 0)
  49819. return result;
  49820. var sqrtD = Math.sqrt(determinant);
  49821. var r1 = (-b - sqrtD) / (2.0 * a);
  49822. var r2 = (-b + sqrtD) / (2.0 * a);
  49823. if (r1 > r2) {
  49824. var temp = r2;
  49825. r2 = r1;
  49826. r1 = temp;
  49827. }
  49828. if (r1 > 0 && r1 < maxR) {
  49829. result.root = r1;
  49830. result.found = true;
  49831. return result;
  49832. }
  49833. if (r2 > 0 && r2 < maxR) {
  49834. result.root = r2;
  49835. result.found = true;
  49836. return result;
  49837. }
  49838. return result;
  49839. };
  49840. })();
  49841. var Collider = /** @class */ (function () {
  49842. function Collider() {
  49843. this._collisionPoint = BABYLON.Vector3.Zero();
  49844. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49845. this._tempVector = BABYLON.Vector3.Zero();
  49846. this._tempVector2 = BABYLON.Vector3.Zero();
  49847. this._tempVector3 = BABYLON.Vector3.Zero();
  49848. this._tempVector4 = BABYLON.Vector3.Zero();
  49849. this._edge = BABYLON.Vector3.Zero();
  49850. this._baseToVertex = BABYLON.Vector3.Zero();
  49851. this._destinationPoint = BABYLON.Vector3.Zero();
  49852. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49853. this._displacementVector = BABYLON.Vector3.Zero();
  49854. this._radius = BABYLON.Vector3.One();
  49855. this._retry = 0;
  49856. this._basePointWorld = BABYLON.Vector3.Zero();
  49857. this._velocityWorld = BABYLON.Vector3.Zero();
  49858. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49859. this._collisionMask = -1;
  49860. }
  49861. Object.defineProperty(Collider.prototype, "collisionMask", {
  49862. get: function () {
  49863. return this._collisionMask;
  49864. },
  49865. set: function (mask) {
  49866. this._collisionMask = !isNaN(mask) ? mask : -1;
  49867. },
  49868. enumerable: true,
  49869. configurable: true
  49870. });
  49871. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49872. /**
  49873. * Gets the plane normal used to compute the sliding response (in local space)
  49874. */
  49875. get: function () {
  49876. return this._slidePlaneNormal;
  49877. },
  49878. enumerable: true,
  49879. configurable: true
  49880. });
  49881. // Methods
  49882. Collider.prototype._initialize = function (source, dir, e) {
  49883. this._velocity = dir;
  49884. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49885. this._basePoint = source;
  49886. source.multiplyToRef(this._radius, this._basePointWorld);
  49887. dir.multiplyToRef(this._radius, this._velocityWorld);
  49888. this._velocityWorldLength = this._velocityWorld.length();
  49889. this._epsilon = e;
  49890. this.collisionFound = false;
  49891. };
  49892. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49893. pa.subtractToRef(point, this._tempVector);
  49894. pb.subtractToRef(point, this._tempVector2);
  49895. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49896. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49897. if (d < 0)
  49898. return false;
  49899. pc.subtractToRef(point, this._tempVector3);
  49900. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49901. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49902. if (d < 0)
  49903. return false;
  49904. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49905. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49906. return d >= 0;
  49907. };
  49908. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49909. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49910. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49911. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49912. return false;
  49913. }
  49914. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49915. return false;
  49916. return true;
  49917. };
  49918. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49919. var t0;
  49920. var embeddedInPlane = false;
  49921. //defensive programming, actually not needed.
  49922. if (!trianglePlaneArray) {
  49923. trianglePlaneArray = [];
  49924. }
  49925. if (!trianglePlaneArray[faceIndex]) {
  49926. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49927. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49928. }
  49929. var trianglePlane = trianglePlaneArray[faceIndex];
  49930. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49931. return;
  49932. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49933. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49934. if (normalDotVelocity == 0) {
  49935. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49936. return;
  49937. embeddedInPlane = true;
  49938. t0 = 0;
  49939. }
  49940. else {
  49941. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49942. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49943. if (t0 > t1) {
  49944. var temp = t1;
  49945. t1 = t0;
  49946. t0 = temp;
  49947. }
  49948. if (t0 > 1.0 || t1 < 0.0)
  49949. return;
  49950. if (t0 < 0)
  49951. t0 = 0;
  49952. if (t0 > 1.0)
  49953. t0 = 1.0;
  49954. }
  49955. this._collisionPoint.copyFromFloats(0, 0, 0);
  49956. var found = false;
  49957. var t = 1.0;
  49958. if (!embeddedInPlane) {
  49959. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49960. this._velocity.scaleToRef(t0, this._tempVector);
  49961. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49962. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49963. found = true;
  49964. t = t0;
  49965. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49966. }
  49967. }
  49968. if (!found) {
  49969. var velocitySquaredLength = this._velocity.lengthSquared();
  49970. var a = velocitySquaredLength;
  49971. this._basePoint.subtractToRef(p1, this._tempVector);
  49972. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49973. var c = this._tempVector.lengthSquared() - 1.0;
  49974. var lowestRoot = getLowestRoot(a, b, c, t);
  49975. if (lowestRoot.found) {
  49976. t = lowestRoot.root;
  49977. found = true;
  49978. this._collisionPoint.copyFrom(p1);
  49979. }
  49980. this._basePoint.subtractToRef(p2, this._tempVector);
  49981. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49982. c = this._tempVector.lengthSquared() - 1.0;
  49983. lowestRoot = getLowestRoot(a, b, c, t);
  49984. if (lowestRoot.found) {
  49985. t = lowestRoot.root;
  49986. found = true;
  49987. this._collisionPoint.copyFrom(p2);
  49988. }
  49989. this._basePoint.subtractToRef(p3, this._tempVector);
  49990. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49991. c = this._tempVector.lengthSquared() - 1.0;
  49992. lowestRoot = getLowestRoot(a, b, c, t);
  49993. if (lowestRoot.found) {
  49994. t = lowestRoot.root;
  49995. found = true;
  49996. this._collisionPoint.copyFrom(p3);
  49997. }
  49998. p2.subtractToRef(p1, this._edge);
  49999. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50000. var edgeSquaredLength = this._edge.lengthSquared();
  50001. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50002. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50003. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50004. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50005. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50006. lowestRoot = getLowestRoot(a, b, c, t);
  50007. if (lowestRoot.found) {
  50008. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50009. if (f >= 0.0 && f <= 1.0) {
  50010. t = lowestRoot.root;
  50011. found = true;
  50012. this._edge.scaleInPlace(f);
  50013. p1.addToRef(this._edge, this._collisionPoint);
  50014. }
  50015. }
  50016. p3.subtractToRef(p2, this._edge);
  50017. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50018. edgeSquaredLength = this._edge.lengthSquared();
  50019. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50020. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50021. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50022. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50023. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50024. lowestRoot = getLowestRoot(a, b, c, t);
  50025. if (lowestRoot.found) {
  50026. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50027. if (f >= 0.0 && f <= 1.0) {
  50028. t = lowestRoot.root;
  50029. found = true;
  50030. this._edge.scaleInPlace(f);
  50031. p2.addToRef(this._edge, this._collisionPoint);
  50032. }
  50033. }
  50034. p1.subtractToRef(p3, this._edge);
  50035. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50036. edgeSquaredLength = this._edge.lengthSquared();
  50037. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50038. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50039. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50040. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50041. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50042. lowestRoot = getLowestRoot(a, b, c, t);
  50043. if (lowestRoot.found) {
  50044. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50045. if (f >= 0.0 && f <= 1.0) {
  50046. t = lowestRoot.root;
  50047. found = true;
  50048. this._edge.scaleInPlace(f);
  50049. p3.addToRef(this._edge, this._collisionPoint);
  50050. }
  50051. }
  50052. }
  50053. if (found) {
  50054. var distToCollision = t * this._velocity.length();
  50055. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50056. if (!this.intersectionPoint) {
  50057. this.intersectionPoint = this._collisionPoint.clone();
  50058. }
  50059. else {
  50060. this.intersectionPoint.copyFrom(this._collisionPoint);
  50061. }
  50062. this._nearestDistance = distToCollision;
  50063. this.collisionFound = true;
  50064. }
  50065. }
  50066. };
  50067. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50068. for (var i = indexStart; i < indexEnd; i += 3) {
  50069. var p1 = pts[indices[i] - decal];
  50070. var p2 = pts[indices[i + 1] - decal];
  50071. var p3 = pts[indices[i + 2] - decal];
  50072. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50073. }
  50074. };
  50075. Collider.prototype._getResponse = function (pos, vel) {
  50076. pos.addToRef(vel, this._destinationPoint);
  50077. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50078. this._basePoint.addToRef(vel, pos);
  50079. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50080. this._slidePlaneNormal.normalize();
  50081. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50082. pos.addInPlace(this._displacementVector);
  50083. this.intersectionPoint.addInPlace(this._displacementVector);
  50084. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50085. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50086. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50087. };
  50088. return Collider;
  50089. }());
  50090. BABYLON.Collider = Collider;
  50091. })(BABYLON || (BABYLON = {}));
  50092. //# sourceMappingURL=babylon.collider.js.map
  50093. var BABYLON;
  50094. (function (BABYLON) {
  50095. //WebWorker code will be inserted to this variable.
  50096. BABYLON.CollisionWorker = "";
  50097. var WorkerTaskType;
  50098. (function (WorkerTaskType) {
  50099. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50100. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50101. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50102. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50103. var WorkerReplyType;
  50104. (function (WorkerReplyType) {
  50105. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50106. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50107. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50108. var CollisionCoordinatorWorker = /** @class */ (function () {
  50109. function CollisionCoordinatorWorker() {
  50110. var _this = this;
  50111. this._scaledPosition = BABYLON.Vector3.Zero();
  50112. this._scaledVelocity = BABYLON.Vector3.Zero();
  50113. this.onMeshUpdated = function (transformNode) {
  50114. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50115. };
  50116. this.onGeometryUpdated = function (geometry) {
  50117. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50118. };
  50119. this._afterRender = function () {
  50120. if (!_this._init)
  50121. return;
  50122. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50123. return;
  50124. }
  50125. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50126. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50127. if (_this._runningUpdated > 4) {
  50128. return;
  50129. }
  50130. ++_this._runningUpdated;
  50131. var payload = {
  50132. updatedMeshes: _this._addUpdateMeshesList,
  50133. updatedGeometries: _this._addUpdateGeometriesList,
  50134. removedGeometries: _this._toRemoveGeometryArray,
  50135. removedMeshes: _this._toRemoveMeshesArray
  50136. };
  50137. var message = {
  50138. payload: payload,
  50139. taskType: WorkerTaskType.UPDATE
  50140. };
  50141. var serializable = [];
  50142. for (var id in payload.updatedGeometries) {
  50143. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50144. //prepare transferables
  50145. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50146. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50147. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50148. }
  50149. }
  50150. _this._worker.postMessage(message, serializable);
  50151. _this._addUpdateMeshesList = {};
  50152. _this._addUpdateGeometriesList = {};
  50153. _this._toRemoveGeometryArray = [];
  50154. _this._toRemoveMeshesArray = [];
  50155. };
  50156. this._onMessageFromWorker = function (e) {
  50157. var returnData = e.data;
  50158. if (returnData.error != WorkerReplyType.SUCCESS) {
  50159. //TODO what errors can be returned from the worker?
  50160. BABYLON.Tools.Warn("error returned from worker!");
  50161. return;
  50162. }
  50163. switch (returnData.taskType) {
  50164. case WorkerTaskType.INIT:
  50165. _this._init = true;
  50166. //Update the worked with ALL of the scene's current state
  50167. _this._scene.meshes.forEach(function (mesh) {
  50168. _this.onMeshAdded(mesh);
  50169. });
  50170. _this._scene.getGeometries().forEach(function (geometry) {
  50171. _this.onGeometryAdded(geometry);
  50172. });
  50173. break;
  50174. case WorkerTaskType.UPDATE:
  50175. _this._runningUpdated--;
  50176. break;
  50177. case WorkerTaskType.COLLIDE:
  50178. var returnPayload = returnData.payload;
  50179. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50180. return;
  50181. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50182. if (callback) {
  50183. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50184. if (mesh) {
  50185. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50186. }
  50187. }
  50188. //cleanup
  50189. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50190. break;
  50191. }
  50192. };
  50193. this._collisionsCallbackArray = [];
  50194. this._init = false;
  50195. this._runningUpdated = 0;
  50196. this._addUpdateMeshesList = {};
  50197. this._addUpdateGeometriesList = {};
  50198. this._toRemoveGeometryArray = [];
  50199. this._toRemoveMeshesArray = [];
  50200. }
  50201. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50202. if (!this._init)
  50203. return;
  50204. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50205. return;
  50206. position.divideToRef(collider._radius, this._scaledPosition);
  50207. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50208. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50209. var payload = {
  50210. collider: {
  50211. position: this._scaledPosition.asArray(),
  50212. velocity: this._scaledVelocity.asArray(),
  50213. radius: collider._radius.asArray()
  50214. },
  50215. collisionId: collisionIndex,
  50216. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50217. maximumRetry: maximumRetry
  50218. };
  50219. var message = {
  50220. payload: payload,
  50221. taskType: WorkerTaskType.COLLIDE
  50222. };
  50223. this._worker.postMessage(message);
  50224. };
  50225. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50226. this._scene = scene;
  50227. this._scene.registerAfterRender(this._afterRender);
  50228. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50229. this._worker = new Worker(workerUrl);
  50230. this._worker.onmessage = this._onMessageFromWorker;
  50231. var message = {
  50232. payload: {},
  50233. taskType: WorkerTaskType.INIT
  50234. };
  50235. this._worker.postMessage(message);
  50236. };
  50237. CollisionCoordinatorWorker.prototype.destroy = function () {
  50238. this._scene.unregisterAfterRender(this._afterRender);
  50239. this._worker.terminate();
  50240. };
  50241. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50242. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50243. this.onMeshUpdated(mesh);
  50244. };
  50245. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50246. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50247. };
  50248. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50249. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50250. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50251. this.onGeometryUpdated(geometry);
  50252. };
  50253. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50254. this._toRemoveGeometryArray.push(geometry.id);
  50255. };
  50256. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50257. var submeshes = [];
  50258. if (mesh.subMeshes) {
  50259. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50260. var boundingInfo = sm.getBoundingInfo();
  50261. return {
  50262. position: idx,
  50263. verticesStart: sm.verticesStart,
  50264. verticesCount: sm.verticesCount,
  50265. indexStart: sm.indexStart,
  50266. indexCount: sm.indexCount,
  50267. hasMaterial: !!sm.getMaterial(),
  50268. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50269. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50270. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50271. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50272. };
  50273. });
  50274. }
  50275. var geometryId = null;
  50276. if (mesh instanceof BABYLON.Mesh) {
  50277. var geometry = mesh.geometry;
  50278. geometryId = geometry ? geometry.id : null;
  50279. }
  50280. else if (mesh instanceof BABYLON.InstancedMesh) {
  50281. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50282. geometryId = geometry ? geometry.id : null;
  50283. }
  50284. var boundingInfo = mesh.getBoundingInfo();
  50285. return {
  50286. uniqueId: mesh.uniqueId,
  50287. id: mesh.id,
  50288. name: mesh.name,
  50289. geometryId: geometryId,
  50290. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50291. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50292. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50293. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50294. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50295. subMeshes: submeshes,
  50296. checkCollisions: mesh.checkCollisions
  50297. };
  50298. };
  50299. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50300. return {
  50301. id: geometry.id,
  50302. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50303. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50304. indices: new Uint32Array(geometry.getIndices() || []),
  50305. };
  50306. };
  50307. return CollisionCoordinatorWorker;
  50308. }());
  50309. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50310. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50311. function CollisionCoordinatorLegacy() {
  50312. this._scaledPosition = BABYLON.Vector3.Zero();
  50313. this._scaledVelocity = BABYLON.Vector3.Zero();
  50314. this._finalPosition = BABYLON.Vector3.Zero();
  50315. }
  50316. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50317. position.divideToRef(collider._radius, this._scaledPosition);
  50318. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50319. collider.collidedMesh = null;
  50320. collider._retry = 0;
  50321. collider._initialVelocity = this._scaledVelocity;
  50322. collider._initialPosition = this._scaledPosition;
  50323. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50324. this._finalPosition.multiplyInPlace(collider._radius);
  50325. //run the callback
  50326. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50327. };
  50328. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50329. this._scene = scene;
  50330. };
  50331. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50332. //Legacy need no destruction method.
  50333. };
  50334. //No update in legacy mode
  50335. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50336. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50337. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50338. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50339. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50340. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50341. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50342. if (excludedMesh === void 0) { excludedMesh = null; }
  50343. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50344. if (collider._retry >= maximumRetry) {
  50345. finalPosition.copyFrom(position);
  50346. return;
  50347. }
  50348. // Check if this is a mesh else camera or -1
  50349. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50350. collider._initialize(position, velocity, closeDistance);
  50351. // Check all meshes
  50352. for (var index = 0; index < this._scene.meshes.length; index++) {
  50353. var mesh = this._scene.meshes[index];
  50354. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50355. mesh._checkCollision(collider);
  50356. }
  50357. }
  50358. if (!collider.collisionFound) {
  50359. position.addToRef(velocity, finalPosition);
  50360. return;
  50361. }
  50362. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50363. collider._getResponse(position, velocity);
  50364. }
  50365. if (velocity.length() <= closeDistance) {
  50366. finalPosition.copyFrom(position);
  50367. return;
  50368. }
  50369. collider._retry++;
  50370. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50371. };
  50372. return CollisionCoordinatorLegacy;
  50373. }());
  50374. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50375. })(BABYLON || (BABYLON = {}));
  50376. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50377. var BABYLON;
  50378. (function (BABYLON) {
  50379. /**
  50380. * A particle represents one of the element emitted by a particle system.
  50381. * This is mainly define by its coordinates, direction, velocity and age.
  50382. */
  50383. var Particle = /** @class */ (function () {
  50384. /**
  50385. * Creates a new instance of @see Particle
  50386. * @param particleSystem the particle system the particle belongs to
  50387. */
  50388. function Particle(particleSystem) {
  50389. this.particleSystem = particleSystem;
  50390. /**
  50391. * The world position of the particle in the scene.
  50392. */
  50393. this.position = BABYLON.Vector3.Zero();
  50394. /**
  50395. * The world direction of the particle in the scene.
  50396. */
  50397. this.direction = BABYLON.Vector3.Zero();
  50398. /**
  50399. * The color of the particle.
  50400. */
  50401. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50402. /**
  50403. * The color change of the particle per step.
  50404. */
  50405. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50406. /**
  50407. * Defines how long will the life of the particle be.
  50408. */
  50409. this.lifeTime = 1.0;
  50410. /**
  50411. * The current age of the particle.
  50412. */
  50413. this.age = 0;
  50414. /**
  50415. * The current size of the particle.
  50416. */
  50417. this.size = 0;
  50418. /**
  50419. * The current angle of the particle.
  50420. */
  50421. this.angle = 0;
  50422. /**
  50423. * Defines how fast is the angle changing.
  50424. */
  50425. this.angularSpeed = 0;
  50426. /**
  50427. * Defines the cell index used by the particle to be rendered from a sprite.
  50428. */
  50429. this.cellIndex = 0;
  50430. this._currentFrameCounter = 0;
  50431. if (!this.particleSystem.isAnimationSheetEnabled) {
  50432. return;
  50433. }
  50434. this.cellIndex = this.particleSystem.startSpriteCellID;
  50435. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50436. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50437. }
  50438. else {
  50439. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50440. }
  50441. }
  50442. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50443. // (ageOffset / scaledUpdateSpeed) / available cells
  50444. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50445. this._currentFrameCounter += scaledUpdateSpeed;
  50446. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50447. this._currentFrameCounter = 0;
  50448. this.cellIndex++;
  50449. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50450. this.cellIndex = this.particleSystem.endSpriteCellID;
  50451. }
  50452. }
  50453. };
  50454. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50455. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50456. this.cellIndex++;
  50457. this._currentFrameCounter = 0;
  50458. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50459. if (this.particleSystem.spriteCellLoop) {
  50460. this.cellIndex = this.particleSystem.startSpriteCellID;
  50461. }
  50462. else {
  50463. this.cellIndex = this.particleSystem.endSpriteCellID;
  50464. }
  50465. }
  50466. }
  50467. else {
  50468. this._currentFrameCounter++;
  50469. }
  50470. };
  50471. /**
  50472. * Copy the properties of particle to another one.
  50473. * @param other the particle to copy the information to.
  50474. */
  50475. Particle.prototype.copyTo = function (other) {
  50476. other.position.copyFrom(this.position);
  50477. other.direction.copyFrom(this.direction);
  50478. other.color.copyFrom(this.color);
  50479. other.colorStep.copyFrom(this.colorStep);
  50480. other.lifeTime = this.lifeTime;
  50481. other.age = this.age;
  50482. other.size = this.size;
  50483. other.angle = this.angle;
  50484. other.angularSpeed = this.angularSpeed;
  50485. other.particleSystem = this.particleSystem;
  50486. other.cellIndex = this.cellIndex;
  50487. };
  50488. return Particle;
  50489. }());
  50490. BABYLON.Particle = Particle;
  50491. })(BABYLON || (BABYLON = {}));
  50492. //# sourceMappingURL=babylon.particle.js.map
  50493. var BABYLON;
  50494. (function (BABYLON) {
  50495. /**
  50496. * This represents a particle system in Babylon.
  50497. * 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.
  50498. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50499. * @example https://doc.babylonjs.com/babylon101/particles
  50500. */
  50501. var ParticleSystem = /** @class */ (function () {
  50502. /**
  50503. * Instantiates a particle system.
  50504. * 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.
  50505. * @param name The name of the particle system
  50506. * @param capacity The max number of particles alive at the same time
  50507. * @param scene The scene the particle system belongs to
  50508. * @param customEffect a custom effect used to change the way particles are rendered by default
  50509. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50510. * @param epsilon Offset used to render the particles
  50511. */
  50512. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50513. if (customEffect === void 0) { customEffect = null; }
  50514. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50515. if (epsilon === void 0) { epsilon = 0.01; }
  50516. var _this = this;
  50517. /**
  50518. * List of animations used by the particle system.
  50519. */
  50520. this.animations = [];
  50521. /**
  50522. * The rendering group used by the Particle system to chose when to render.
  50523. */
  50524. this.renderingGroupId = 0;
  50525. /**
  50526. * The emitter represents the Mesh or position we are attaching the particle system to.
  50527. */
  50528. this.emitter = null;
  50529. /**
  50530. * The maximum number of particles to emit per frame
  50531. */
  50532. this.emitRate = 10;
  50533. /**
  50534. * If you want to launch only a few particles at once, that can be done, as well.
  50535. */
  50536. this.manualEmitCount = -1;
  50537. /**
  50538. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50539. */
  50540. this.updateSpeed = 0.01;
  50541. /**
  50542. * The amount of time the particle system is running (depends of the overall update speed).
  50543. */
  50544. this.targetStopDuration = 0;
  50545. /**
  50546. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50547. */
  50548. this.disposeOnStop = false;
  50549. /**
  50550. * Minimum power of emitting particles.
  50551. */
  50552. this.minEmitPower = 1;
  50553. /**
  50554. * Maximum power of emitting particles.
  50555. */
  50556. this.maxEmitPower = 1;
  50557. /**
  50558. * Minimum life time of emitting particles.
  50559. */
  50560. this.minLifeTime = 1;
  50561. /**
  50562. * Maximum life time of emitting particles.
  50563. */
  50564. this.maxLifeTime = 1;
  50565. /**
  50566. * Minimum Size of emitting particles.
  50567. */
  50568. this.minSize = 1;
  50569. /**
  50570. * Maximum Size of emitting particles.
  50571. */
  50572. this.maxSize = 1;
  50573. /**
  50574. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50575. */
  50576. this.minAngularSpeed = 0;
  50577. /**
  50578. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50579. */
  50580. this.maxAngularSpeed = 0;
  50581. /**
  50582. * The layer mask we are rendering the particles through.
  50583. */
  50584. this.layerMask = 0x0FFFFFFF;
  50585. /**
  50586. * This can help using your own shader to render the particle system.
  50587. * The according effect will be created
  50588. */
  50589. this.customShader = null;
  50590. /**
  50591. * By default particle system starts as soon as they are created. This prevents the
  50592. * automatic start to happen and let you decide when to start emitting particles.
  50593. */
  50594. this.preventAutoStart = false;
  50595. /**
  50596. * Callback triggered when the particle animation is ending.
  50597. */
  50598. this.onAnimationEnd = null;
  50599. /**
  50600. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50601. */
  50602. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50603. /**
  50604. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50605. * to override the particles.
  50606. */
  50607. this.forceDepthWrite = false;
  50608. /**
  50609. * You can use gravity if you want to give an orientation to your particles.
  50610. */
  50611. this.gravity = BABYLON.Vector3.Zero();
  50612. /**
  50613. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50614. */
  50615. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50616. /**
  50617. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50618. */
  50619. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50620. /**
  50621. * Color the particle will have at the end of its lifetime.
  50622. */
  50623. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50624. /**
  50625. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50626. */
  50627. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50628. /**
  50629. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50630. */
  50631. this.spriteCellLoop = true;
  50632. /**
  50633. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50634. */
  50635. this.spriteCellChangeSpeed = 0;
  50636. /**
  50637. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50638. */
  50639. this.startSpriteCellID = 0;
  50640. /**
  50641. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50642. */
  50643. this.endSpriteCellID = 0;
  50644. /**
  50645. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50646. */
  50647. this.spriteCellWidth = 0;
  50648. /**
  50649. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50650. */
  50651. this.spriteCellHeight = 0;
  50652. /**
  50653. * An event triggered when the system is disposed.
  50654. */
  50655. this.onDisposeObservable = new BABYLON.Observable();
  50656. this._particles = new Array();
  50657. this._stockParticles = new Array();
  50658. this._newPartsExcess = 0;
  50659. this._vertexBuffers = {};
  50660. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50661. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50662. this._scaledDirection = BABYLON.Vector3.Zero();
  50663. this._scaledGravity = BABYLON.Vector3.Zero();
  50664. this._currentRenderId = -1;
  50665. this._started = false;
  50666. this._stopped = false;
  50667. this._actualFrame = 0;
  50668. this._vertexBufferSize = 11;
  50669. this._appendParticleVertexes = null;
  50670. this.id = name;
  50671. this.name = name;
  50672. this._capacity = capacity;
  50673. this._epsilon = epsilon;
  50674. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50675. if (isAnimationSheetEnabled) {
  50676. this._vertexBufferSize = 12;
  50677. }
  50678. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50679. this._customEffect = customEffect;
  50680. scene.particleSystems.push(this);
  50681. this._createIndexBuffer();
  50682. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50683. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50684. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50685. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50686. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50687. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50688. if (this._isAnimationSheetEnabled) {
  50689. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50690. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50691. }
  50692. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50693. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50694. this._vertexBuffers["options"] = options;
  50695. // Default emitter type
  50696. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50697. this.updateFunction = function (particles) {
  50698. for (var index = 0; index < particles.length; index++) {
  50699. var particle = particles[index];
  50700. particle.age += _this._scaledUpdateSpeed;
  50701. if (particle.age >= particle.lifeTime) {
  50702. _this.recycleParticle(particle);
  50703. index--;
  50704. continue;
  50705. }
  50706. else {
  50707. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50708. particle.color.addInPlace(_this._scaledColorStep);
  50709. if (particle.color.a < 0)
  50710. particle.color.a = 0;
  50711. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50712. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50713. particle.position.addInPlace(_this._scaledDirection);
  50714. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50715. particle.direction.addInPlace(_this._scaledGravity);
  50716. if (_this._isAnimationSheetEnabled) {
  50717. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50718. }
  50719. }
  50720. }
  50721. };
  50722. }
  50723. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50724. /**
  50725. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50726. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50727. */
  50728. get: function () {
  50729. if (this.particleEmitterType.direction1) {
  50730. return this.particleEmitterType.direction1;
  50731. }
  50732. return BABYLON.Vector3.Zero();
  50733. },
  50734. set: function (value) {
  50735. if (this.particleEmitterType.direction1) {
  50736. this.particleEmitterType.direction1 = value;
  50737. }
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50743. /**
  50744. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50745. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50746. */
  50747. get: function () {
  50748. if (this.particleEmitterType.direction2) {
  50749. return this.particleEmitterType.direction2;
  50750. }
  50751. return BABYLON.Vector3.Zero();
  50752. },
  50753. set: function (value) {
  50754. if (this.particleEmitterType.direction2) {
  50755. this.particleEmitterType.direction2 = value;
  50756. }
  50757. },
  50758. enumerable: true,
  50759. configurable: true
  50760. });
  50761. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50762. /**
  50763. * 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.
  50764. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50765. */
  50766. get: function () {
  50767. if (this.particleEmitterType.minEmitBox) {
  50768. return this.particleEmitterType.minEmitBox;
  50769. }
  50770. return BABYLON.Vector3.Zero();
  50771. },
  50772. set: function (value) {
  50773. if (this.particleEmitterType.minEmitBox) {
  50774. this.particleEmitterType.minEmitBox = value;
  50775. }
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50781. /**
  50782. * 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.
  50783. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50784. */
  50785. get: function () {
  50786. if (this.particleEmitterType.maxEmitBox) {
  50787. return this.particleEmitterType.maxEmitBox;
  50788. }
  50789. return BABYLON.Vector3.Zero();
  50790. },
  50791. set: function (value) {
  50792. if (this.particleEmitterType.maxEmitBox) {
  50793. this.particleEmitterType.maxEmitBox = value;
  50794. }
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50800. /**
  50801. * Sets a callback that will be triggered when the system is disposed.
  50802. */
  50803. set: function (callback) {
  50804. if (this._onDisposeObserver) {
  50805. this.onDisposeObservable.remove(this._onDisposeObserver);
  50806. }
  50807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50808. },
  50809. enumerable: true,
  50810. configurable: true
  50811. });
  50812. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50813. /**
  50814. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50815. */
  50816. get: function () {
  50817. return this._isAnimationSheetEnabled;
  50818. },
  50819. enumerable: true,
  50820. configurable: true
  50821. });
  50822. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50823. /**
  50824. * Gets the current list of active particles
  50825. */
  50826. get: function () {
  50827. return this._particles;
  50828. },
  50829. enumerable: true,
  50830. configurable: true
  50831. });
  50832. /**
  50833. * Returns the string "ParticleSystem"
  50834. * @returns a string containing the class name
  50835. */
  50836. ParticleSystem.prototype.getClassName = function () {
  50837. return "ParticleSystem";
  50838. };
  50839. ParticleSystem.prototype._createIndexBuffer = function () {
  50840. var indices = [];
  50841. var index = 0;
  50842. for (var count = 0; count < this._capacity; count++) {
  50843. indices.push(index);
  50844. indices.push(index + 1);
  50845. indices.push(index + 2);
  50846. indices.push(index);
  50847. indices.push(index + 2);
  50848. indices.push(index + 3);
  50849. index += 4;
  50850. }
  50851. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50852. };
  50853. /**
  50854. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50855. * Its lifetime will start back at 0.
  50856. * @param particle The particle to recycle
  50857. */
  50858. ParticleSystem.prototype.recycleParticle = function (particle) {
  50859. var lastParticle = this._particles.pop();
  50860. if (lastParticle !== particle) {
  50861. lastParticle.copyTo(particle);
  50862. this._stockParticles.push(lastParticle);
  50863. }
  50864. };
  50865. /**
  50866. * Gets the maximum number of particles active at the same time.
  50867. * @returns The max number of active particles.
  50868. */
  50869. ParticleSystem.prototype.getCapacity = function () {
  50870. return this._capacity;
  50871. };
  50872. /**
  50873. * Gets Wether there are still active particles in the system.
  50874. * @returns True if it is alive, otherwise false.
  50875. */
  50876. ParticleSystem.prototype.isAlive = function () {
  50877. return this._alive;
  50878. };
  50879. /**
  50880. * Gets Wether the system has been started.
  50881. * @returns True if it has been started, otherwise false.
  50882. */
  50883. ParticleSystem.prototype.isStarted = function () {
  50884. return this._started;
  50885. };
  50886. /**
  50887. * Starts the particle system and begins to emit.
  50888. */
  50889. ParticleSystem.prototype.start = function () {
  50890. this._started = true;
  50891. this._stopped = false;
  50892. this._actualFrame = 0;
  50893. };
  50894. /**
  50895. * Stops the particle system.
  50896. */
  50897. ParticleSystem.prototype.stop = function () {
  50898. this._stopped = true;
  50899. };
  50900. /**
  50901. * Remove all active particles
  50902. */
  50903. ParticleSystem.prototype.reset = function () {
  50904. this._stockParticles = [];
  50905. this._particles = [];
  50906. };
  50907. /**
  50908. * @ignore (for internal use only)
  50909. */
  50910. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50911. var offset = index * this._vertexBufferSize;
  50912. this._vertexData[offset] = particle.position.x;
  50913. this._vertexData[offset + 1] = particle.position.y;
  50914. this._vertexData[offset + 2] = particle.position.z;
  50915. this._vertexData[offset + 3] = particle.color.r;
  50916. this._vertexData[offset + 4] = particle.color.g;
  50917. this._vertexData[offset + 5] = particle.color.b;
  50918. this._vertexData[offset + 6] = particle.color.a;
  50919. this._vertexData[offset + 7] = particle.angle;
  50920. this._vertexData[offset + 8] = particle.size;
  50921. this._vertexData[offset + 9] = offsetX;
  50922. this._vertexData[offset + 10] = offsetY;
  50923. };
  50924. /**
  50925. * @ignore (for internal use only)
  50926. */
  50927. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50928. if (offsetX === 0)
  50929. offsetX = this._epsilon;
  50930. else if (offsetX === 1)
  50931. offsetX = 1 - this._epsilon;
  50932. if (offsetY === 0)
  50933. offsetY = this._epsilon;
  50934. else if (offsetY === 1)
  50935. offsetY = 1 - this._epsilon;
  50936. var offset = index * this._vertexBufferSize;
  50937. this._vertexData[offset] = particle.position.x;
  50938. this._vertexData[offset + 1] = particle.position.y;
  50939. this._vertexData[offset + 2] = particle.position.z;
  50940. this._vertexData[offset + 3] = particle.color.r;
  50941. this._vertexData[offset + 4] = particle.color.g;
  50942. this._vertexData[offset + 5] = particle.color.b;
  50943. this._vertexData[offset + 6] = particle.color.a;
  50944. this._vertexData[offset + 7] = particle.angle;
  50945. this._vertexData[offset + 8] = particle.size;
  50946. this._vertexData[offset + 9] = offsetX;
  50947. this._vertexData[offset + 10] = offsetY;
  50948. this._vertexData[offset + 11] = particle.cellIndex;
  50949. };
  50950. ParticleSystem.prototype._update = function (newParticles) {
  50951. // Update current
  50952. this._alive = this._particles.length > 0;
  50953. this.updateFunction(this._particles);
  50954. // Add new ones
  50955. var worldMatrix;
  50956. if (this.emitter.position) {
  50957. var emitterMesh = this.emitter;
  50958. worldMatrix = emitterMesh.getWorldMatrix();
  50959. }
  50960. else {
  50961. var emitterPosition = this.emitter;
  50962. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50963. }
  50964. var particle;
  50965. for (var index = 0; index < newParticles; index++) {
  50966. if (this._particles.length === this._capacity) {
  50967. break;
  50968. }
  50969. if (this._stockParticles.length !== 0) {
  50970. particle = this._stockParticles.pop();
  50971. particle.age = 0;
  50972. particle.cellIndex = this.startSpriteCellID;
  50973. }
  50974. else {
  50975. particle = new BABYLON.Particle(this);
  50976. }
  50977. this._particles.push(particle);
  50978. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50979. if (this.startPositionFunction) {
  50980. this.startPositionFunction(worldMatrix, particle.position, particle);
  50981. }
  50982. else {
  50983. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50984. }
  50985. if (this.startDirectionFunction) {
  50986. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50987. }
  50988. else {
  50989. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50990. }
  50991. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50992. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50993. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50994. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50995. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50996. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50997. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50998. }
  50999. };
  51000. ParticleSystem.prototype._getEffect = function () {
  51001. if (this._customEffect) {
  51002. return this._customEffect;
  51003. }
  51004. ;
  51005. var defines = [];
  51006. if (this._scene.clipPlane) {
  51007. defines.push("#define CLIPPLANE");
  51008. }
  51009. if (this._isAnimationSheetEnabled) {
  51010. defines.push("#define ANIMATESHEET");
  51011. }
  51012. // Effect
  51013. var join = defines.join("\n");
  51014. if (this._cachedDefines !== join) {
  51015. this._cachedDefines = join;
  51016. var attributesNamesOrOptions;
  51017. var effectCreationOption;
  51018. if (this._isAnimationSheetEnabled) {
  51019. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51020. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51021. }
  51022. else {
  51023. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51024. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51025. }
  51026. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51027. }
  51028. return this._effect;
  51029. };
  51030. /**
  51031. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51032. */
  51033. ParticleSystem.prototype.animate = function () {
  51034. if (!this._started)
  51035. return;
  51036. var effect = this._getEffect();
  51037. // Check
  51038. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51039. return;
  51040. if (this._currentRenderId === this._scene.getRenderId()) {
  51041. return;
  51042. }
  51043. this._currentRenderId = this._scene.getRenderId();
  51044. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51045. // determine the number of particles we need to create
  51046. var newParticles;
  51047. if (this.manualEmitCount > -1) {
  51048. newParticles = this.manualEmitCount;
  51049. this._newPartsExcess = 0;
  51050. this.manualEmitCount = 0;
  51051. }
  51052. else {
  51053. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51054. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51055. }
  51056. if (this._newPartsExcess > 1.0) {
  51057. newParticles += this._newPartsExcess >> 0;
  51058. this._newPartsExcess -= this._newPartsExcess >> 0;
  51059. }
  51060. this._alive = false;
  51061. if (!this._stopped) {
  51062. this._actualFrame += this._scaledUpdateSpeed;
  51063. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51064. this.stop();
  51065. }
  51066. else {
  51067. newParticles = 0;
  51068. }
  51069. this._update(newParticles);
  51070. // Stopped?
  51071. if (this._stopped) {
  51072. if (!this._alive) {
  51073. this._started = false;
  51074. if (this.onAnimationEnd) {
  51075. this.onAnimationEnd();
  51076. }
  51077. if (this.disposeOnStop) {
  51078. this._scene._toBeDisposed.push(this);
  51079. }
  51080. }
  51081. }
  51082. // Animation sheet
  51083. if (this._isAnimationSheetEnabled) {
  51084. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51085. }
  51086. else {
  51087. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51088. }
  51089. // Update VBO
  51090. var offset = 0;
  51091. for (var index = 0; index < this._particles.length; index++) {
  51092. var particle = this._particles[index];
  51093. this._appendParticleVertexes(offset, particle);
  51094. offset += 4;
  51095. }
  51096. if (this._vertexBuffer) {
  51097. this._vertexBuffer.update(this._vertexData);
  51098. }
  51099. };
  51100. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51101. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51102. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51103. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51104. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51105. };
  51106. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51107. this._appendParticleVertex(offset++, particle, 0, 0);
  51108. this._appendParticleVertex(offset++, particle, 1, 0);
  51109. this._appendParticleVertex(offset++, particle, 1, 1);
  51110. this._appendParticleVertex(offset++, particle, 0, 1);
  51111. };
  51112. /**
  51113. * Rebuilds the particle system.
  51114. */
  51115. ParticleSystem.prototype.rebuild = function () {
  51116. this._createIndexBuffer();
  51117. if (this._vertexBuffer) {
  51118. this._vertexBuffer._rebuild();
  51119. }
  51120. };
  51121. /**
  51122. * Renders the particle system in its current state.
  51123. * @returns the current number of particles
  51124. */
  51125. ParticleSystem.prototype.render = function () {
  51126. var effect = this._getEffect();
  51127. // Check
  51128. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51129. return 0;
  51130. }
  51131. var engine = this._scene.getEngine();
  51132. // Render
  51133. engine.enableEffect(effect);
  51134. engine.setState(false);
  51135. var viewMatrix = this._scene.getViewMatrix();
  51136. effect.setTexture("diffuseSampler", this.particleTexture);
  51137. effect.setMatrix("view", viewMatrix);
  51138. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51139. if (this._isAnimationSheetEnabled) {
  51140. var baseSize = this.particleTexture.getBaseSize();
  51141. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51142. }
  51143. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51144. if (this._scene.clipPlane) {
  51145. var clipPlane = this._scene.clipPlane;
  51146. var invView = viewMatrix.clone();
  51147. invView.invert();
  51148. effect.setMatrix("invView", invView);
  51149. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51150. }
  51151. // VBOs
  51152. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51153. // Draw order
  51154. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51155. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51156. }
  51157. else {
  51158. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51159. }
  51160. if (this.forceDepthWrite) {
  51161. engine.setDepthWrite(true);
  51162. }
  51163. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51165. return this._particles.length;
  51166. };
  51167. /**
  51168. * Disposes the particle system and free the associated resources
  51169. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51170. */
  51171. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51172. if (disposeTexture === void 0) { disposeTexture = true; }
  51173. if (this._vertexBuffer) {
  51174. this._vertexBuffer.dispose();
  51175. this._vertexBuffer = null;
  51176. }
  51177. if (this._indexBuffer) {
  51178. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51179. this._indexBuffer = null;
  51180. }
  51181. if (disposeTexture && this.particleTexture) {
  51182. this.particleTexture.dispose();
  51183. this.particleTexture = null;
  51184. }
  51185. // Remove from scene
  51186. var index = this._scene.particleSystems.indexOf(this);
  51187. if (index > -1) {
  51188. this._scene.particleSystems.splice(index, 1);
  51189. }
  51190. // Callback
  51191. this.onDisposeObservable.notifyObservers(this);
  51192. this.onDisposeObservable.clear();
  51193. };
  51194. /**
  51195. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51196. * @param radius The radius of the sphere to emit from
  51197. * @returns the emitter
  51198. */
  51199. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51200. if (radius === void 0) { radius = 1; }
  51201. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51202. this.particleEmitterType = particleEmitter;
  51203. return particleEmitter;
  51204. };
  51205. /**
  51206. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51207. * @param radius The radius of the sphere to emit from
  51208. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51209. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51210. * @returns the emitter
  51211. */
  51212. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51213. if (radius === void 0) { radius = 1; }
  51214. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51215. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51216. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51217. this.particleEmitterType = particleEmitter;
  51218. return particleEmitter;
  51219. };
  51220. /**
  51221. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51222. * @param radius The radius of the cone to emit from
  51223. * @param angle The base angle of the cone
  51224. * @returns the emitter
  51225. */
  51226. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51227. if (radius === void 0) { radius = 1; }
  51228. if (angle === void 0) { angle = Math.PI / 4; }
  51229. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51230. this.particleEmitterType = particleEmitter;
  51231. return particleEmitter;
  51232. };
  51233. // 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.
  51234. /**
  51235. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51236. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51237. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51238. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51239. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51240. * @returns the emitter
  51241. */
  51242. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51243. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51244. this.direction1 = direction1;
  51245. this.direction2 = direction2;
  51246. this.minEmitBox = minEmitBox;
  51247. this.maxEmitBox = maxEmitBox;
  51248. this.particleEmitterType = particleEmitter;
  51249. return particleEmitter;
  51250. };
  51251. /**
  51252. * Clones the particle system.
  51253. * @param name The name of the cloned object
  51254. * @param newEmitter The new emitter to use
  51255. * @returns the cloned particle system
  51256. */
  51257. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51258. var custom = null;
  51259. var program = null;
  51260. if (this.customShader != null) {
  51261. program = this.customShader;
  51262. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51263. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51264. }
  51265. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51266. result.customShader = program;
  51267. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51268. if (newEmitter === undefined) {
  51269. newEmitter = this.emitter;
  51270. }
  51271. result.emitter = newEmitter;
  51272. if (this.particleTexture) {
  51273. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51274. }
  51275. if (!this.preventAutoStart) {
  51276. result.start();
  51277. }
  51278. return result;
  51279. };
  51280. /**
  51281. * Serializes the particle system to a JSON object.
  51282. * @returns the JSON object
  51283. */
  51284. ParticleSystem.prototype.serialize = function () {
  51285. var serializationObject = {};
  51286. serializationObject.name = this.name;
  51287. serializationObject.id = this.id;
  51288. // Emitter
  51289. if (this.emitter.position) {
  51290. var emitterMesh = this.emitter;
  51291. serializationObject.emitterId = emitterMesh.id;
  51292. }
  51293. else {
  51294. var emitterPosition = this.emitter;
  51295. serializationObject.emitter = emitterPosition.asArray();
  51296. }
  51297. serializationObject.capacity = this.getCapacity();
  51298. if (this.particleTexture) {
  51299. serializationObject.textureName = this.particleTexture.name;
  51300. }
  51301. // Animations
  51302. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51303. // Particle system
  51304. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51305. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51306. serializationObject.minSize = this.minSize;
  51307. serializationObject.maxSize = this.maxSize;
  51308. serializationObject.minEmitPower = this.minEmitPower;
  51309. serializationObject.maxEmitPower = this.maxEmitPower;
  51310. serializationObject.minLifeTime = this.minLifeTime;
  51311. serializationObject.maxLifeTime = this.maxLifeTime;
  51312. serializationObject.emitRate = this.emitRate;
  51313. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51314. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51315. serializationObject.gravity = this.gravity.asArray();
  51316. serializationObject.direction1 = this.direction1.asArray();
  51317. serializationObject.direction2 = this.direction2.asArray();
  51318. serializationObject.color1 = this.color1.asArray();
  51319. serializationObject.color2 = this.color2.asArray();
  51320. serializationObject.colorDead = this.colorDead.asArray();
  51321. serializationObject.updateSpeed = this.updateSpeed;
  51322. serializationObject.targetStopDuration = this.targetStopDuration;
  51323. serializationObject.textureMask = this.textureMask.asArray();
  51324. serializationObject.blendMode = this.blendMode;
  51325. serializationObject.customShader = this.customShader;
  51326. serializationObject.preventAutoStart = this.preventAutoStart;
  51327. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51328. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51329. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51330. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51331. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51332. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51333. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51334. // Emitter
  51335. if (this.particleEmitterType) {
  51336. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51337. }
  51338. return serializationObject;
  51339. };
  51340. /**
  51341. * Parses a JSON object to create a particle system.
  51342. * @param parsedParticleSystem The JSON object to parse
  51343. * @param scene The scene to create the particle system in
  51344. * @param rootUrl The root url to use to load external dependencies like texture
  51345. * @returns the Parsed particle system
  51346. */
  51347. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51348. var name = parsedParticleSystem.name;
  51349. var custom = null;
  51350. var program = null;
  51351. if (parsedParticleSystem.customShader) {
  51352. program = parsedParticleSystem.customShader;
  51353. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51354. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51355. }
  51356. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51357. particleSystem.customShader = program;
  51358. if (parsedParticleSystem.id) {
  51359. particleSystem.id = parsedParticleSystem.id;
  51360. }
  51361. // Auto start
  51362. if (parsedParticleSystem.preventAutoStart) {
  51363. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51364. }
  51365. // Texture
  51366. if (parsedParticleSystem.textureName) {
  51367. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51368. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51369. }
  51370. // Emitter
  51371. if (parsedParticleSystem.emitterId) {
  51372. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51373. }
  51374. else {
  51375. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51376. }
  51377. // Animations
  51378. if (parsedParticleSystem.animations) {
  51379. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51380. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51381. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51382. }
  51383. }
  51384. if (parsedParticleSystem.autoAnimate) {
  51385. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51386. }
  51387. // Particle system
  51388. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51389. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51390. particleSystem.minSize = parsedParticleSystem.minSize;
  51391. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51392. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51393. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51394. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51395. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51396. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51397. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51398. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51399. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51400. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51401. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51402. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51403. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51404. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51405. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51406. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51407. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51408. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51409. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51410. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51411. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51412. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51413. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51414. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51415. if (!particleSystem.preventAutoStart) {
  51416. particleSystem.start();
  51417. }
  51418. return particleSystem;
  51419. };
  51420. /**
  51421. * Source color is added to the destination color without alpha affecting the result.
  51422. */
  51423. ParticleSystem.BLENDMODE_ONEONE = 0;
  51424. /**
  51425. * Blend current color and particle color using particle’s alpha.
  51426. */
  51427. ParticleSystem.BLENDMODE_STANDARD = 1;
  51428. return ParticleSystem;
  51429. }());
  51430. BABYLON.ParticleSystem = ParticleSystem;
  51431. })(BABYLON || (BABYLON = {}));
  51432. //# sourceMappingURL=babylon.particleSystem.js.map
  51433. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51434. var BABYLON;
  51435. (function (BABYLON) {
  51436. /**
  51437. * Particle emitter emitting particles from the inside of a box.
  51438. * It emits the particles randomly between 2 given directions.
  51439. */
  51440. var BoxParticleEmitter = /** @class */ (function () {
  51441. /**
  51442. * Creates a new instance of @see BoxParticleEmitter
  51443. */
  51444. function BoxParticleEmitter() {
  51445. /**
  51446. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51447. */
  51448. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51449. /**
  51450. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51451. */
  51452. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51453. /**
  51454. * 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.
  51455. */
  51456. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51457. /**
  51458. * 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.
  51459. */
  51460. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51461. }
  51462. /**
  51463. * Called by the particle System when the direction is computed for the created particle.
  51464. * @param emitPower is the power of the particle (speed)
  51465. * @param worldMatrix is the world matrix of the particle system
  51466. * @param directionToUpdate is the direction vector to update with the result
  51467. * @param particle is the particle we are computed the direction for
  51468. */
  51469. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51470. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51471. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51472. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51473. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51474. };
  51475. /**
  51476. * Called by the particle System when the position is computed for the created particle.
  51477. * @param worldMatrix is the world matrix of the particle system
  51478. * @param positionToUpdate is the position vector to update with the result
  51479. * @param particle is the particle we are computed the position for
  51480. */
  51481. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51482. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51483. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51484. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51486. };
  51487. /**
  51488. * Clones the current emitter and returns a copy of it
  51489. * @returns the new emitter
  51490. */
  51491. BoxParticleEmitter.prototype.clone = function () {
  51492. var newOne = new BoxParticleEmitter();
  51493. BABYLON.Tools.DeepCopy(this, newOne);
  51494. return newOne;
  51495. };
  51496. /**
  51497. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51498. * @param effect defines the update shader
  51499. */
  51500. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51501. effect.setVector3("direction1", this.direction1);
  51502. effect.setVector3("direction2", this.direction2);
  51503. effect.setVector3("minEmitBox", this.minEmitBox);
  51504. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51505. };
  51506. /**
  51507. * Returns a string to use to update the GPU particles update shader
  51508. * @returns a string containng the defines string
  51509. */
  51510. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51511. return "#define BOXEMITTER";
  51512. };
  51513. /**
  51514. * Returns the string "BoxEmitter"
  51515. * @returns a string containing the class name
  51516. */
  51517. BoxParticleEmitter.prototype.getClassName = function () {
  51518. return "BoxEmitter";
  51519. };
  51520. /**
  51521. * Serializes the particle system to a JSON object.
  51522. * @returns the JSON object
  51523. */
  51524. BoxParticleEmitter.prototype.serialize = function () {
  51525. var serializationObject = {};
  51526. serializationObject.type = this.getClassName();
  51527. serializationObject.direction1 = this.direction1.asArray();
  51528. ;
  51529. serializationObject.direction2 = this.direction2.asArray();
  51530. ;
  51531. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51532. ;
  51533. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51534. ;
  51535. return serializationObject;
  51536. };
  51537. /**
  51538. * Parse properties from a JSON object
  51539. * @param serializationObject defines the JSON object
  51540. */
  51541. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51542. this.direction1.copyFrom(serializationObject.direction1);
  51543. this.direction2.copyFrom(serializationObject.direction2);
  51544. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51545. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51546. };
  51547. return BoxParticleEmitter;
  51548. }());
  51549. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51550. })(BABYLON || (BABYLON = {}));
  51551. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51552. var BABYLON;
  51553. (function (BABYLON) {
  51554. /**
  51555. * Particle emitter emitting particles from the inside of a cone.
  51556. * It emits the particles alongside the cone volume from the base to the particle.
  51557. * The emission direction might be randomized.
  51558. */
  51559. var ConeParticleEmitter = /** @class */ (function () {
  51560. /**
  51561. * Creates a new instance of @see ConeParticleEmitter
  51562. * @param radius the radius of the emission cone (1 by default)
  51563. * @param angles the cone base angle (PI by default)
  51564. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51565. */
  51566. function ConeParticleEmitter(radius,
  51567. /**
  51568. * The radius of the emission cone.
  51569. */
  51570. angle,
  51571. /**
  51572. * The cone base angle.
  51573. */
  51574. directionRandomizer) {
  51575. if (radius === void 0) { radius = 1; }
  51576. if (angle === void 0) { angle = Math.PI; }
  51577. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51578. this.angle = angle;
  51579. this.directionRandomizer = directionRandomizer;
  51580. this.radius = radius;
  51581. }
  51582. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51583. /**
  51584. * Gets the radius of the emission cone.
  51585. */
  51586. get: function () {
  51587. return this._radius;
  51588. },
  51589. /**
  51590. * Sets the radius of the emission cone.
  51591. */
  51592. set: function (value) {
  51593. this._radius = value;
  51594. if (this.angle !== 0) {
  51595. this._height = value / Math.tan(this.angle / 2);
  51596. }
  51597. else {
  51598. this._height = 1;
  51599. }
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. /**
  51605. * Called by the particle System when the direction is computed for the created particle.
  51606. * @param emitPower is the power of the particle (speed)
  51607. * @param worldMatrix is the world matrix of the particle system
  51608. * @param directionToUpdate is the direction vector to update with the result
  51609. * @param particle is the particle we are computed the direction for
  51610. */
  51611. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51612. if (this.angle === 0) {
  51613. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51614. }
  51615. else {
  51616. // measure the direction Vector from the emitter to the particle.
  51617. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51618. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51619. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51620. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51621. direction.x += randX;
  51622. direction.y += randY;
  51623. direction.z += randZ;
  51624. direction.normalize();
  51625. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51626. }
  51627. };
  51628. /**
  51629. * Called by the particle System when the position is computed for the created particle.
  51630. * @param worldMatrix is the world matrix of the particle system
  51631. * @param positionToUpdate is the position vector to update with the result
  51632. * @param particle is the particle we are computed the position for
  51633. */
  51634. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51635. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51636. var h = BABYLON.Scalar.RandomRange(0, 1);
  51637. // Better distribution in a cone at normal angles.
  51638. h = 1 - h * h;
  51639. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51640. radius = radius * h / this._height;
  51641. var randX = radius * Math.sin(s);
  51642. var randZ = radius * Math.cos(s);
  51643. var randY = h * this._height;
  51644. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51645. };
  51646. /**
  51647. * Clones the current emitter and returns a copy of it
  51648. * @returns the new emitter
  51649. */
  51650. ConeParticleEmitter.prototype.clone = function () {
  51651. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51652. BABYLON.Tools.DeepCopy(this, newOne);
  51653. return newOne;
  51654. };
  51655. /**
  51656. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51657. * @param effect defines the update shader
  51658. */
  51659. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51660. effect.setFloat("radius", this.radius);
  51661. effect.setFloat("angle", this.angle);
  51662. effect.setFloat("height", this._height);
  51663. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51664. };
  51665. /**
  51666. * Returns a string to use to update the GPU particles update shader
  51667. * @returns a string containng the defines string
  51668. */
  51669. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51670. return "#define CONEEMITTER";
  51671. };
  51672. /**
  51673. * Returns the string "BoxEmitter"
  51674. * @returns a string containing the class name
  51675. */
  51676. ConeParticleEmitter.prototype.getClassName = function () {
  51677. return "ConeEmitter";
  51678. };
  51679. /**
  51680. * Serializes the particle system to a JSON object.
  51681. * @returns the JSON object
  51682. */
  51683. ConeParticleEmitter.prototype.serialize = function () {
  51684. var serializationObject = {};
  51685. serializationObject.type = this.getClassName();
  51686. serializationObject.radius = this.radius;
  51687. serializationObject.angle = this.angle;
  51688. serializationObject.directionRandomizer = this.directionRandomizer;
  51689. return serializationObject;
  51690. };
  51691. /**
  51692. * Parse properties from a JSON object
  51693. * @param serializationObject defines the JSON object
  51694. */
  51695. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51696. this.radius = serializationObject.radius;
  51697. this.angle = serializationObject.angle;
  51698. this.directionRandomizer = serializationObject.directionRandomizer;
  51699. };
  51700. return ConeParticleEmitter;
  51701. }());
  51702. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51703. })(BABYLON || (BABYLON = {}));
  51704. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51705. var BABYLON;
  51706. (function (BABYLON) {
  51707. /**
  51708. * Particle emitter emitting particles from the inside of a sphere.
  51709. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51710. */
  51711. var SphereParticleEmitter = /** @class */ (function () {
  51712. /**
  51713. * Creates a new instance of @see SphereParticleEmitter
  51714. * @param radius the radius of the emission sphere (1 by default)
  51715. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51716. */
  51717. function SphereParticleEmitter(
  51718. /**
  51719. * The radius of the emission sphere.
  51720. */
  51721. radius,
  51722. /**
  51723. * How much to randomize the particle direction [0-1].
  51724. */
  51725. directionRandomizer) {
  51726. if (radius === void 0) { radius = 1; }
  51727. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51728. this.radius = radius;
  51729. this.directionRandomizer = directionRandomizer;
  51730. }
  51731. /**
  51732. * Called by the particle System when the direction is computed for the created particle.
  51733. * @param emitPower is the power of the particle (speed)
  51734. * @param worldMatrix is the world matrix of the particle system
  51735. * @param directionToUpdate is the direction vector to update with the result
  51736. * @param particle is the particle we are computed the direction for
  51737. */
  51738. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51739. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51740. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51741. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51742. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51743. direction.x += randX;
  51744. direction.y += randY;
  51745. direction.z += randZ;
  51746. direction.normalize();
  51747. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51748. };
  51749. /**
  51750. * Called by the particle System when the position is computed for the created particle.
  51751. * @param worldMatrix is the world matrix of the particle system
  51752. * @param positionToUpdate is the position vector to update with the result
  51753. * @param particle is the particle we are computed the position for
  51754. */
  51755. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51756. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51757. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51758. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51759. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51760. var randY = randRadius * Math.cos(theta);
  51761. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51762. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51763. };
  51764. /**
  51765. * Clones the current emitter and returns a copy of it
  51766. * @returns the new emitter
  51767. */
  51768. SphereParticleEmitter.prototype.clone = function () {
  51769. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51770. BABYLON.Tools.DeepCopy(this, newOne);
  51771. return newOne;
  51772. };
  51773. /**
  51774. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51775. * @param effect defines the update shader
  51776. */
  51777. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51778. effect.setFloat("radius", this.radius);
  51779. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51780. };
  51781. /**
  51782. * Returns a string to use to update the GPU particles update shader
  51783. * @returns a string containng the defines string
  51784. */
  51785. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51786. return "#define SPHEREEMITTER";
  51787. };
  51788. /**
  51789. * Returns the string "SphereParticleEmitter"
  51790. * @returns a string containing the class name
  51791. */
  51792. SphereParticleEmitter.prototype.getClassName = function () {
  51793. return "SphereParticleEmitter";
  51794. };
  51795. /**
  51796. * Serializes the particle system to a JSON object.
  51797. * @returns the JSON object
  51798. */
  51799. SphereParticleEmitter.prototype.serialize = function () {
  51800. var serializationObject = {};
  51801. serializationObject.type = this.getClassName();
  51802. serializationObject.radius = this.radius;
  51803. serializationObject.directionRandomizer = this.directionRandomizer;
  51804. return serializationObject;
  51805. };
  51806. /**
  51807. * Parse properties from a JSON object
  51808. * @param serializationObject defines the JSON object
  51809. */
  51810. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51811. this.radius = serializationObject.radius;
  51812. this.directionRandomizer = serializationObject.directionRandomizer;
  51813. };
  51814. return SphereParticleEmitter;
  51815. }());
  51816. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51817. /**
  51818. * Particle emitter emitting particles from the inside of a sphere.
  51819. * It emits the particles randomly between two vectors.
  51820. */
  51821. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51822. __extends(SphereDirectedParticleEmitter, _super);
  51823. /**
  51824. * Creates a new instance of @see SphereDirectedParticleEmitter
  51825. * @param radius the radius of the emission sphere (1 by default)
  51826. * @param direction1 the min limit of the emission direction (up vector by default)
  51827. * @param direction2 the max limit of the emission direction (up vector by default)
  51828. */
  51829. function SphereDirectedParticleEmitter(radius,
  51830. /**
  51831. * The min limit of the emission direction.
  51832. */
  51833. direction1,
  51834. /**
  51835. * The max limit of the emission direction.
  51836. */
  51837. direction2) {
  51838. if (radius === void 0) { radius = 1; }
  51839. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51840. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51841. var _this = _super.call(this, radius) || this;
  51842. _this.direction1 = direction1;
  51843. _this.direction2 = direction2;
  51844. return _this;
  51845. }
  51846. /**
  51847. * Called by the particle System when the direction is computed for the created particle.
  51848. * @param emitPower is the power of the particle (speed)
  51849. * @param worldMatrix is the world matrix of the particle system
  51850. * @param directionToUpdate is the direction vector to update with the result
  51851. * @param particle is the particle we are computed the direction for
  51852. */
  51853. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51854. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51855. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51856. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51857. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51858. };
  51859. /**
  51860. * Clones the current emitter and returns a copy of it
  51861. * @returns the new emitter
  51862. */
  51863. SphereDirectedParticleEmitter.prototype.clone = function () {
  51864. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51865. BABYLON.Tools.DeepCopy(this, newOne);
  51866. return newOne;
  51867. };
  51868. /**
  51869. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51870. * @param effect defines the update shader
  51871. */
  51872. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51873. effect.setFloat("radius", this.radius);
  51874. effect.setVector3("direction1", this.direction1);
  51875. effect.setVector3("direction2", this.direction2);
  51876. };
  51877. /**
  51878. * Returns a string to use to update the GPU particles update shader
  51879. * @returns a string containng the defines string
  51880. */
  51881. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51882. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51883. };
  51884. /**
  51885. * Returns the string "SphereDirectedParticleEmitter"
  51886. * @returns a string containing the class name
  51887. */
  51888. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51889. return "SphereDirectedParticleEmitter";
  51890. };
  51891. /**
  51892. * Serializes the particle system to a JSON object.
  51893. * @returns the JSON object
  51894. */
  51895. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51896. var serializationObject = _super.prototype.serialize.call(this);
  51897. ;
  51898. serializationObject.direction1 = this.direction1.asArray();
  51899. ;
  51900. serializationObject.direction2 = this.direction2.asArray();
  51901. ;
  51902. return serializationObject;
  51903. };
  51904. /**
  51905. * Parse properties from a JSON object
  51906. * @param serializationObject defines the JSON object
  51907. */
  51908. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51909. _super.prototype.parse.call(this, serializationObject);
  51910. this.direction1.copyFrom(serializationObject.direction1);
  51911. this.direction2.copyFrom(serializationObject.direction2);
  51912. };
  51913. return SphereDirectedParticleEmitter;
  51914. }(SphereParticleEmitter));
  51915. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51916. })(BABYLON || (BABYLON = {}));
  51917. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51918. var BABYLON;
  51919. (function (BABYLON) {
  51920. /**
  51921. * Represents one particle of a solid particle system.
  51922. * @see SolidParticleSystem
  51923. */
  51924. var SolidParticle = /** @class */ (function () {
  51925. /**
  51926. * Creates a Solid Particle object.
  51927. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51928. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51929. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51930. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51931. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51932. * @param shapeId (integer) is the model shape identifier in the SPS.
  51933. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51934. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51935. */
  51936. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51937. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51938. /**
  51939. * particle global index
  51940. */
  51941. this.idx = 0;
  51942. /**
  51943. * The color of the particle
  51944. */
  51945. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51946. /**
  51947. * The world space position of the particle.
  51948. */
  51949. this.position = BABYLON.Vector3.Zero();
  51950. /**
  51951. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51952. */
  51953. this.rotation = BABYLON.Vector3.Zero();
  51954. /**
  51955. * The scaling of the particle.
  51956. */
  51957. this.scaling = BABYLON.Vector3.One();
  51958. /**
  51959. * The uvs of the particle.
  51960. */
  51961. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51962. /**
  51963. * The current speed of the particle.
  51964. */
  51965. this.velocity = BABYLON.Vector3.Zero();
  51966. /**
  51967. * The pivot point in the particle local space.
  51968. */
  51969. this.pivot = BABYLON.Vector3.Zero();
  51970. /**
  51971. * Must the particle be translated from its pivot point in its local space ?
  51972. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51973. * Default : false
  51974. */
  51975. this.translateFromPivot = false;
  51976. /**
  51977. * Is the particle active or not ?
  51978. */
  51979. this.alive = true;
  51980. /**
  51981. * Is the particle visible or not ?
  51982. */
  51983. this.isVisible = true;
  51984. /**
  51985. * Index of this particle in the global "positions" array (Internal use)
  51986. */
  51987. this._pos = 0;
  51988. /**
  51989. * Index of this particle in the global "indices" array (Internal use)
  51990. */
  51991. this._ind = 0;
  51992. /**
  51993. * ModelShape id of this particle
  51994. */
  51995. this.shapeId = 0;
  51996. /**
  51997. * Index of the particle in its shape id (Internal use)
  51998. */
  51999. this.idxInShape = 0;
  52000. /**
  52001. * Still set as invisible in order to skip useless computations (Internal use)
  52002. */
  52003. this._stillInvisible = false;
  52004. /**
  52005. * Last computed particle rotation matrix
  52006. */
  52007. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52008. /**
  52009. * Parent particle Id, if any.
  52010. * Default null.
  52011. */
  52012. this.parentId = null;
  52013. /**
  52014. * Internal global position in the SPS.
  52015. */
  52016. this._globalPosition = BABYLON.Vector3.Zero();
  52017. this.idx = particleIndex;
  52018. this._pos = positionIndex;
  52019. this._ind = indiceIndex;
  52020. this._model = model;
  52021. this.shapeId = shapeId;
  52022. this.idxInShape = idxInShape;
  52023. this._sps = sps;
  52024. if (modelBoundingInfo) {
  52025. this._modelBoundingInfo = modelBoundingInfo;
  52026. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52027. }
  52028. }
  52029. Object.defineProperty(SolidParticle.prototype, "scale", {
  52030. /**
  52031. * Legacy support, changed scale to scaling
  52032. */
  52033. get: function () {
  52034. return this.scaling;
  52035. },
  52036. /**
  52037. * Legacy support, changed scale to scaling
  52038. */
  52039. set: function (scale) {
  52040. this.scaling = scale;
  52041. },
  52042. enumerable: true,
  52043. configurable: true
  52044. });
  52045. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52046. /**
  52047. * Legacy support, changed quaternion to rotationQuaternion
  52048. */
  52049. get: function () {
  52050. return this.rotationQuaternion;
  52051. },
  52052. /**
  52053. * Legacy support, changed quaternion to rotationQuaternion
  52054. */
  52055. set: function (q) {
  52056. this.rotationQuaternion = q;
  52057. },
  52058. enumerable: true,
  52059. configurable: true
  52060. });
  52061. /**
  52062. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52063. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52064. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52065. * @returns true if it intersects
  52066. */
  52067. SolidParticle.prototype.intersectsMesh = function (target) {
  52068. if (!this._boundingInfo || !target._boundingInfo) {
  52069. return false;
  52070. }
  52071. if (this._sps._bSphereOnly) {
  52072. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52073. }
  52074. return this._boundingInfo.intersects(target._boundingInfo, false);
  52075. };
  52076. return SolidParticle;
  52077. }());
  52078. BABYLON.SolidParticle = SolidParticle;
  52079. /**
  52080. * Represents the shape of the model used by one particle of a solid particle system.
  52081. * SPS internal tool, don't use it manually.
  52082. * @see SolidParticleSystem
  52083. */
  52084. var ModelShape = /** @class */ (function () {
  52085. /**
  52086. * 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.
  52087. * SPS internal tool, don't use it manually.
  52088. * @ignore
  52089. */
  52090. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52091. /**
  52092. * length of the shape in the model indices array (internal use)
  52093. */
  52094. this._indicesLength = 0;
  52095. this.shapeID = id;
  52096. this._shape = shape;
  52097. this._indicesLength = indicesLength;
  52098. this._shapeUV = shapeUV;
  52099. this._positionFunction = posFunction;
  52100. this._vertexFunction = vtxFunction;
  52101. }
  52102. return ModelShape;
  52103. }());
  52104. BABYLON.ModelShape = ModelShape;
  52105. /**
  52106. * Represents a Depth Sorted Particle in the solid particle system.
  52107. * @see SolidParticleSystem
  52108. */
  52109. var DepthSortedParticle = /** @class */ (function () {
  52110. function DepthSortedParticle() {
  52111. /**
  52112. * Index of the particle in the "indices" array
  52113. */
  52114. this.ind = 0;
  52115. /**
  52116. * Length of the particle shape in the "indices" array
  52117. */
  52118. this.indicesLength = 0;
  52119. /**
  52120. * Squared distance from the particle to the camera
  52121. */
  52122. this.sqDistance = 0.0;
  52123. }
  52124. return DepthSortedParticle;
  52125. }());
  52126. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52127. })(BABYLON || (BABYLON = {}));
  52128. //# sourceMappingURL=babylon.solidParticle.js.map
  52129. var BABYLON;
  52130. (function (BABYLON) {
  52131. /**
  52132. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52133. *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.
  52134. * The SPS is also a particle system. It provides some methods to manage the particles.
  52135. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52136. *
  52137. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52138. */
  52139. var SolidParticleSystem = /** @class */ (function () {
  52140. /**
  52141. * Creates a SPS (Solid Particle System) object.
  52142. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52143. * @param scene (Scene) is the scene in which the SPS is added.
  52144. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52145. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52146. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52147. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52148. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52149. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52150. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52151. */
  52152. function SolidParticleSystem(name, scene, options) {
  52153. /**
  52154. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52155. * Example : var p = SPS.particles[i];
  52156. */
  52157. this.particles = new Array();
  52158. /**
  52159. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52160. */
  52161. this.nbParticles = 0;
  52162. /**
  52163. * If the particles must ever face the camera (default false). Useful for planar particles.
  52164. */
  52165. this.billboard = false;
  52166. /**
  52167. * Recompute normals when adding a shape
  52168. */
  52169. this.recomputeNormals = true;
  52170. /**
  52171. * This a counter ofr your own usage. It's not set by any SPS functions.
  52172. */
  52173. this.counter = 0;
  52174. /**
  52175. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52176. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52177. */
  52178. this.vars = {};
  52179. /**
  52180. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52181. */
  52182. this._bSphereOnly = false;
  52183. /**
  52184. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52185. */
  52186. this._bSphereRadiusFactor = 1.0;
  52187. this._positions = new Array();
  52188. this._indices = new Array();
  52189. this._normals = new Array();
  52190. this._colors = new Array();
  52191. this._uvs = new Array();
  52192. this._index = 0; // indices index
  52193. this._updatable = true;
  52194. this._pickable = false;
  52195. this._isVisibilityBoxLocked = false;
  52196. this._alwaysVisible = false;
  52197. this._depthSort = false;
  52198. this._shapeCounter = 0;
  52199. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52200. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52201. this._computeParticleColor = true;
  52202. this._computeParticleTexture = true;
  52203. this._computeParticleRotation = true;
  52204. this._computeParticleVertex = false;
  52205. this._computeBoundingBox = false;
  52206. this._depthSortParticles = true;
  52207. this._cam_axisZ = BABYLON.Vector3.Zero();
  52208. this._cam_axisY = BABYLON.Vector3.Zero();
  52209. this._cam_axisX = BABYLON.Vector3.Zero();
  52210. this._axisZ = BABYLON.Axis.Z;
  52211. this._camDir = BABYLON.Vector3.Zero();
  52212. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52213. this._rotMatrix = new BABYLON.Matrix();
  52214. this._invertMatrix = new BABYLON.Matrix();
  52215. this._rotated = BABYLON.Vector3.Zero();
  52216. this._quaternion = new BABYLON.Quaternion();
  52217. this._vertex = BABYLON.Vector3.Zero();
  52218. this._normal = BABYLON.Vector3.Zero();
  52219. this._yaw = 0.0;
  52220. this._pitch = 0.0;
  52221. this._roll = 0.0;
  52222. this._halfroll = 0.0;
  52223. this._halfpitch = 0.0;
  52224. this._halfyaw = 0.0;
  52225. this._sinRoll = 0.0;
  52226. this._cosRoll = 0.0;
  52227. this._sinPitch = 0.0;
  52228. this._cosPitch = 0.0;
  52229. this._sinYaw = 0.0;
  52230. this._cosYaw = 0.0;
  52231. this._mustUnrotateFixedNormals = false;
  52232. this._minimum = BABYLON.Vector3.Zero();
  52233. this._maximum = BABYLON.Vector3.Zero();
  52234. this._minBbox = BABYLON.Vector3.Zero();
  52235. this._maxBbox = BABYLON.Vector3.Zero();
  52236. this._particlesIntersect = false;
  52237. this._depthSortFunction = function (p1, p2) {
  52238. return (p2.sqDistance - p1.sqDistance);
  52239. };
  52240. this._needs32Bits = false;
  52241. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52242. this._scaledPivot = BABYLON.Vector3.Zero();
  52243. this._particleHasParent = false;
  52244. this.name = name;
  52245. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52246. this._camera = scene.activeCamera;
  52247. this._pickable = options ? options.isPickable : false;
  52248. this._depthSort = options ? options.enableDepthSort : false;
  52249. this._particlesIntersect = options ? options.particleIntersection : false;
  52250. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52251. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52252. if (options && options.updatable) {
  52253. this._updatable = options.updatable;
  52254. }
  52255. else {
  52256. this._updatable = true;
  52257. }
  52258. if (this._pickable) {
  52259. this.pickedParticles = [];
  52260. }
  52261. if (this._depthSort) {
  52262. this.depthSortedParticles = [];
  52263. }
  52264. }
  52265. /**
  52266. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52267. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52268. * @returns the created mesh
  52269. */
  52270. SolidParticleSystem.prototype.buildMesh = function () {
  52271. if (this.nbParticles === 0) {
  52272. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52273. this.addShape(triangle, 1);
  52274. triangle.dispose();
  52275. }
  52276. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52277. this._positions32 = new Float32Array(this._positions);
  52278. this._uvs32 = new Float32Array(this._uvs);
  52279. this._colors32 = new Float32Array(this._colors);
  52280. if (this.recomputeNormals) {
  52281. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52282. }
  52283. this._normals32 = new Float32Array(this._normals);
  52284. this._fixedNormal32 = new Float32Array(this._normals);
  52285. if (this._mustUnrotateFixedNormals) {
  52286. this._unrotateFixedNormals();
  52287. }
  52288. var vertexData = new BABYLON.VertexData();
  52289. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52290. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52291. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52292. if (this._uvs32) {
  52293. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52294. ;
  52295. }
  52296. if (this._colors32) {
  52297. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52298. }
  52299. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52300. vertexData.applyToMesh(mesh, this._updatable);
  52301. this.mesh = mesh;
  52302. this.mesh.isPickable = this._pickable;
  52303. // free memory
  52304. if (!this._depthSort) {
  52305. this._indices = null;
  52306. }
  52307. this._positions = null;
  52308. this._normals = null;
  52309. this._uvs = null;
  52310. this._colors = null;
  52311. if (!this._updatable) {
  52312. this.particles.length = 0;
  52313. }
  52314. return mesh;
  52315. };
  52316. /**
  52317. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52318. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52319. * Thus the particles generated from `digest()` have their property `position` set yet.
  52320. * @param mesh ( Mesh ) is the mesh to be digested
  52321. * @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
  52322. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52323. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52324. * @returns the current SPS
  52325. */
  52326. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52327. var size = (options && options.facetNb) || 1;
  52328. var number = (options && options.number) || 0;
  52329. var delta = (options && options.delta) || 0;
  52330. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52331. var meshInd = mesh.getIndices();
  52332. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52333. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52334. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52335. var f = 0; // facet counter
  52336. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52337. // compute size from number
  52338. if (number) {
  52339. number = (number > totalFacets) ? totalFacets : number;
  52340. size = Math.round(totalFacets / number);
  52341. delta = 0;
  52342. }
  52343. else {
  52344. size = (size > totalFacets) ? totalFacets : size;
  52345. }
  52346. var facetPos = []; // submesh positions
  52347. var facetInd = []; // submesh indices
  52348. var facetUV = []; // submesh UV
  52349. var facetCol = []; // submesh colors
  52350. var barycenter = BABYLON.Vector3.Zero();
  52351. var sizeO = size;
  52352. while (f < totalFacets) {
  52353. size = sizeO + Math.floor((1 + delta) * Math.random());
  52354. if (f > totalFacets - size) {
  52355. size = totalFacets - f;
  52356. }
  52357. // reset temp arrays
  52358. facetPos.length = 0;
  52359. facetInd.length = 0;
  52360. facetUV.length = 0;
  52361. facetCol.length = 0;
  52362. // iterate over "size" facets
  52363. var fi = 0;
  52364. for (var j = f * 3; j < (f + size) * 3; j++) {
  52365. facetInd.push(fi);
  52366. var i = meshInd[j];
  52367. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52368. if (meshUV) {
  52369. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52370. }
  52371. if (meshCol) {
  52372. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52373. }
  52374. fi++;
  52375. }
  52376. // create a model shape for each single particle
  52377. var idx = this.nbParticles;
  52378. var shape = this._posToShape(facetPos);
  52379. var shapeUV = this._uvsToShapeUV(facetUV);
  52380. // compute the barycenter of the shape
  52381. var v;
  52382. for (v = 0; v < shape.length; v++) {
  52383. barycenter.addInPlace(shape[v]);
  52384. }
  52385. barycenter.scaleInPlace(1 / shape.length);
  52386. // shift the shape from its barycenter to the origin
  52387. for (v = 0; v < shape.length; v++) {
  52388. shape[v].subtractInPlace(barycenter);
  52389. }
  52390. var bInfo;
  52391. if (this._particlesIntersect) {
  52392. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52393. }
  52394. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52395. // add the particle in the SPS
  52396. var currentPos = this._positions.length;
  52397. var currentInd = this._indices.length;
  52398. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52399. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52400. // initialize the particle position
  52401. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52402. this._index += shape.length;
  52403. idx++;
  52404. this.nbParticles++;
  52405. this._shapeCounter++;
  52406. f += size;
  52407. }
  52408. return this;
  52409. };
  52410. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52411. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52412. var index = 0;
  52413. var idx = 0;
  52414. for (var p = 0; p < this.particles.length; p++) {
  52415. this._particle = this.particles[p];
  52416. this._shape = this._particle._model._shape;
  52417. if (this._particle.rotationQuaternion) {
  52418. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52419. }
  52420. else {
  52421. this._yaw = this._particle.rotation.y;
  52422. this._pitch = this._particle.rotation.x;
  52423. this._roll = this._particle.rotation.z;
  52424. this._quaternionRotationYPR();
  52425. }
  52426. this._quaternionToRotationMatrix();
  52427. this._rotMatrix.invertToRef(this._invertMatrix);
  52428. for (var pt = 0; pt < this._shape.length; pt++) {
  52429. idx = index + pt * 3;
  52430. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52431. this._fixedNormal32[idx] = this._normal.x;
  52432. this._fixedNormal32[idx + 1] = this._normal.y;
  52433. this._fixedNormal32[idx + 2] = this._normal.z;
  52434. }
  52435. index = idx + 3;
  52436. }
  52437. };
  52438. //reset copy
  52439. SolidParticleSystem.prototype._resetCopy = function () {
  52440. this._copy.position.x = 0;
  52441. this._copy.position.y = 0;
  52442. this._copy.position.z = 0;
  52443. this._copy.rotation.x = 0;
  52444. this._copy.rotation.y = 0;
  52445. this._copy.rotation.z = 0;
  52446. this._copy.rotationQuaternion = null;
  52447. this._copy.scaling.x = 1.0;
  52448. this._copy.scaling.y = 1.0;
  52449. this._copy.scaling.z = 1.0;
  52450. this._copy.uvs.x = 0;
  52451. this._copy.uvs.y = 0;
  52452. this._copy.uvs.z = 1.0;
  52453. this._copy.uvs.w = 1.0;
  52454. this._copy.color = null;
  52455. this._copy.translateFromPivot = false;
  52456. };
  52457. // _meshBuilder : inserts the shape model in the global SPS mesh
  52458. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52459. var i;
  52460. var u = 0;
  52461. var c = 0;
  52462. var n = 0;
  52463. this._resetCopy();
  52464. if (options && options.positionFunction) {
  52465. options.positionFunction(this._copy, idx, idxInShape);
  52466. this._mustUnrotateFixedNormals = true;
  52467. }
  52468. if (this._copy.rotationQuaternion) {
  52469. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52470. }
  52471. else {
  52472. this._yaw = this._copy.rotation.y;
  52473. this._pitch = this._copy.rotation.x;
  52474. this._roll = this._copy.rotation.z;
  52475. this._quaternionRotationYPR();
  52476. }
  52477. this._quaternionToRotationMatrix();
  52478. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52479. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52480. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52481. if (this._copy.translateFromPivot) {
  52482. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52483. }
  52484. else {
  52485. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52486. }
  52487. for (i = 0; i < shape.length; i++) {
  52488. this._vertex.x = shape[i].x;
  52489. this._vertex.y = shape[i].y;
  52490. this._vertex.z = shape[i].z;
  52491. if (options && options.vertexFunction) {
  52492. options.vertexFunction(this._copy, this._vertex, i);
  52493. }
  52494. this._vertex.x *= this._copy.scaling.x;
  52495. this._vertex.y *= this._copy.scaling.y;
  52496. this._vertex.z *= this._copy.scaling.z;
  52497. this._vertex.x -= this._scaledPivot.x;
  52498. this._vertex.y -= this._scaledPivot.y;
  52499. this._vertex.z -= this._scaledPivot.z;
  52500. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52501. this._rotated.addInPlace(this._pivotBackTranslation);
  52502. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52503. if (meshUV) {
  52504. 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);
  52505. u += 2;
  52506. }
  52507. if (this._copy.color) {
  52508. this._color = this._copy.color;
  52509. }
  52510. else if (meshCol && meshCol[c] !== undefined) {
  52511. this._color.r = meshCol[c];
  52512. this._color.g = meshCol[c + 1];
  52513. this._color.b = meshCol[c + 2];
  52514. this._color.a = meshCol[c + 3];
  52515. }
  52516. else {
  52517. this._color.r = 1.0;
  52518. this._color.g = 1.0;
  52519. this._color.b = 1.0;
  52520. this._color.a = 1.0;
  52521. }
  52522. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52523. c += 4;
  52524. if (!this.recomputeNormals && meshNor) {
  52525. this._normal.x = meshNor[n];
  52526. this._normal.y = meshNor[n + 1];
  52527. this._normal.z = meshNor[n + 2];
  52528. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52529. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52530. n += 3;
  52531. }
  52532. }
  52533. for (i = 0; i < meshInd.length; i++) {
  52534. var current_ind = p + meshInd[i];
  52535. indices.push(current_ind);
  52536. if (current_ind > 65535) {
  52537. this._needs32Bits = true;
  52538. }
  52539. }
  52540. if (this._pickable) {
  52541. var nbfaces = meshInd.length / 3;
  52542. for (i = 0; i < nbfaces; i++) {
  52543. this.pickedParticles.push({ idx: idx, faceId: i });
  52544. }
  52545. }
  52546. if (this._depthSort) {
  52547. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52548. }
  52549. return this._copy;
  52550. };
  52551. // returns a shape array from positions array
  52552. SolidParticleSystem.prototype._posToShape = function (positions) {
  52553. var shape = [];
  52554. for (var i = 0; i < positions.length; i += 3) {
  52555. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52556. }
  52557. return shape;
  52558. };
  52559. // returns a shapeUV array from a Vector4 uvs
  52560. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52561. var shapeUV = [];
  52562. if (uvs) {
  52563. for (var i = 0; i < uvs.length; i++)
  52564. shapeUV.push(uvs[i]);
  52565. }
  52566. return shapeUV;
  52567. };
  52568. // adds a new particle object in the particles array
  52569. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52570. if (bInfo === void 0) { bInfo = null; }
  52571. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52572. this.particles.push(sp);
  52573. return sp;
  52574. };
  52575. /**
  52576. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52577. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52578. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52579. * @param nb (positive integer) the number of particles to be created from this model
  52580. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52581. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52582. * @returns the number of shapes in the system
  52583. */
  52584. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52585. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52586. var meshInd = mesh.getIndices();
  52587. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52588. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52589. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52590. var bbInfo;
  52591. if (this._particlesIntersect) {
  52592. bbInfo = mesh.getBoundingInfo();
  52593. }
  52594. var shape = this._posToShape(meshPos);
  52595. var shapeUV = this._uvsToShapeUV(meshUV);
  52596. var posfunc = options ? options.positionFunction : null;
  52597. var vtxfunc = options ? options.vertexFunction : null;
  52598. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52599. // particles
  52600. var sp;
  52601. var currentCopy;
  52602. var idx = this.nbParticles;
  52603. for (var i = 0; i < nb; i++) {
  52604. var currentPos = this._positions.length;
  52605. var currentInd = this._indices.length;
  52606. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52607. if (this._updatable) {
  52608. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52609. sp.position.copyFrom(currentCopy.position);
  52610. sp.rotation.copyFrom(currentCopy.rotation);
  52611. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52612. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52613. }
  52614. if (currentCopy.color && sp.color) {
  52615. sp.color.copyFrom(currentCopy.color);
  52616. }
  52617. sp.scaling.copyFrom(currentCopy.scaling);
  52618. sp.uvs.copyFrom(currentCopy.uvs);
  52619. }
  52620. this._index += shape.length;
  52621. idx++;
  52622. }
  52623. this.nbParticles += nb;
  52624. this._shapeCounter++;
  52625. return this._shapeCounter - 1;
  52626. };
  52627. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52628. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52629. this._resetCopy();
  52630. if (particle._model._positionFunction) {
  52631. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52632. }
  52633. if (this._copy.rotationQuaternion) {
  52634. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52635. }
  52636. else {
  52637. this._yaw = this._copy.rotation.y;
  52638. this._pitch = this._copy.rotation.x;
  52639. this._roll = this._copy.rotation.z;
  52640. this._quaternionRotationYPR();
  52641. }
  52642. this._quaternionToRotationMatrix();
  52643. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52644. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52645. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52646. if (this._copy.translateFromPivot) {
  52647. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52648. }
  52649. else {
  52650. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52651. }
  52652. this._shape = particle._model._shape;
  52653. for (var pt = 0; pt < this._shape.length; pt++) {
  52654. this._vertex.x = this._shape[pt].x;
  52655. this._vertex.y = this._shape[pt].y;
  52656. this._vertex.z = this._shape[pt].z;
  52657. if (particle._model._vertexFunction) {
  52658. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52659. }
  52660. this._vertex.x *= this._copy.scaling.x;
  52661. this._vertex.y *= this._copy.scaling.y;
  52662. this._vertex.z *= this._copy.scaling.z;
  52663. this._vertex.x -= this._scaledPivot.x;
  52664. this._vertex.y -= this._scaledPivot.y;
  52665. this._vertex.z -= this._scaledPivot.z;
  52666. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52667. this._rotated.addInPlace(this._pivotBackTranslation);
  52668. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52669. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52670. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52671. }
  52672. particle.position.x = 0.0;
  52673. particle.position.y = 0.0;
  52674. particle.position.z = 0.0;
  52675. particle.rotation.x = 0.0;
  52676. particle.rotation.y = 0.0;
  52677. particle.rotation.z = 0.0;
  52678. particle.rotationQuaternion = null;
  52679. particle.scaling.x = 1.0;
  52680. particle.scaling.y = 1.0;
  52681. particle.scaling.z = 1.0;
  52682. particle.uvs.x = 0.0;
  52683. particle.uvs.y = 0.0;
  52684. particle.uvs.z = 1.0;
  52685. particle.uvs.w = 1.0;
  52686. particle.pivot.x = 0.0;
  52687. particle.pivot.y = 0.0;
  52688. particle.pivot.z = 0.0;
  52689. particle.translateFromPivot = false;
  52690. particle.parentId = null;
  52691. };
  52692. /**
  52693. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52694. * @returns the SPS.
  52695. */
  52696. SolidParticleSystem.prototype.rebuildMesh = function () {
  52697. for (var p = 0; p < this.particles.length; p++) {
  52698. this._rebuildParticle(this.particles[p]);
  52699. }
  52700. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52701. return this;
  52702. };
  52703. /**
  52704. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52705. * This method calls `updateParticle()` for each particle of the SPS.
  52706. * For an animated SPS, it is usually called within the render loop.
  52707. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52708. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52709. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52710. * @returns the SPS.
  52711. */
  52712. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52713. if (start === void 0) { start = 0; }
  52714. if (end === void 0) { end = this.nbParticles - 1; }
  52715. if (update === void 0) { update = true; }
  52716. if (!this._updatable) {
  52717. return this;
  52718. }
  52719. // custom beforeUpdate
  52720. this.beforeUpdateParticles(start, end, update);
  52721. this._cam_axisX.x = 1.0;
  52722. this._cam_axisX.y = 0.0;
  52723. this._cam_axisX.z = 0.0;
  52724. this._cam_axisY.x = 0.0;
  52725. this._cam_axisY.y = 1.0;
  52726. this._cam_axisY.z = 0.0;
  52727. this._cam_axisZ.x = 0.0;
  52728. this._cam_axisZ.y = 0.0;
  52729. this._cam_axisZ.z = 1.0;
  52730. // cases when the World Matrix is to be computed first
  52731. if (this.billboard || this._depthSort) {
  52732. this.mesh.computeWorldMatrix(true);
  52733. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52734. }
  52735. // if the particles will always face the camera
  52736. if (this.billboard) {
  52737. // compute the camera position and un-rotate it by the current mesh rotation
  52738. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52739. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52740. this._cam_axisZ.normalize();
  52741. // same for camera up vector extracted from the cam view matrix
  52742. var view = this._camera.getViewMatrix(true);
  52743. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52744. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52745. this._cam_axisY.normalize();
  52746. this._cam_axisX.normalize();
  52747. }
  52748. // if depthSort, compute the camera global position in the mesh local system
  52749. if (this._depthSort) {
  52750. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52751. }
  52752. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52753. var idx = 0; // current position index in the global array positions32
  52754. var index = 0; // position start index in the global array positions32 of the current particle
  52755. var colidx = 0; // current color index in the global array colors32
  52756. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52757. var uvidx = 0; // current uv index in the global array uvs32
  52758. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52759. var pt = 0; // current index in the particle model shape
  52760. if (this.mesh.isFacetDataEnabled) {
  52761. this._computeBoundingBox = true;
  52762. }
  52763. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52764. if (this._computeBoundingBox) {
  52765. if (start == 0 && end == this.nbParticles - 1) {
  52766. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52767. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52768. }
  52769. else {
  52770. if (this.mesh._boundingInfo) {
  52771. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52772. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52773. }
  52774. }
  52775. }
  52776. // particle loop
  52777. index = this.particles[start]._pos;
  52778. var vpos = (index / 3) | 0;
  52779. colorIndex = vpos * 4;
  52780. uvIndex = vpos * 2;
  52781. for (var p = start; p <= end; p++) {
  52782. this._particle = this.particles[p];
  52783. this._shape = this._particle._model._shape;
  52784. this._shapeUV = this._particle._model._shapeUV;
  52785. // call to custom user function to update the particle properties
  52786. this.updateParticle(this._particle);
  52787. // camera-particle distance for depth sorting
  52788. if (this._depthSort && this._depthSortParticles) {
  52789. var dsp = this.depthSortedParticles[p];
  52790. dsp.ind = this._particle._ind;
  52791. dsp.indicesLength = this._particle._model._indicesLength;
  52792. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52793. }
  52794. // skip the computations for inactive or already invisible particles
  52795. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52796. // increment indexes for the next particle
  52797. pt = this._shape.length;
  52798. index += pt * 3;
  52799. colorIndex += pt * 4;
  52800. uvIndex += pt * 2;
  52801. continue;
  52802. }
  52803. if (this._particle.isVisible) {
  52804. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52805. this._particleHasParent = (this._particle.parentId !== null);
  52806. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52807. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52808. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52809. // particle rotation matrix
  52810. if (this.billboard) {
  52811. this._particle.rotation.x = 0.0;
  52812. this._particle.rotation.y = 0.0;
  52813. }
  52814. if (this._computeParticleRotation || this.billboard) {
  52815. if (this._particle.rotationQuaternion) {
  52816. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52817. }
  52818. else {
  52819. this._yaw = this._particle.rotation.y;
  52820. this._pitch = this._particle.rotation.x;
  52821. this._roll = this._particle.rotation.z;
  52822. this._quaternionRotationYPR();
  52823. }
  52824. this._quaternionToRotationMatrix();
  52825. }
  52826. if (this._particleHasParent) {
  52827. this._parent = this.particles[this._particle.parentId];
  52828. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  52829. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  52830. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  52831. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52832. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52833. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52834. if (this._computeParticleRotation || this.billboard) {
  52835. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  52836. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  52837. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  52838. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  52839. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  52840. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  52841. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  52842. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  52843. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  52844. }
  52845. }
  52846. else {
  52847. this._particle._globalPosition.x = this._particle.position.x;
  52848. this._particle._globalPosition.y = this._particle.position.y;
  52849. this._particle._globalPosition.z = this._particle.position.z;
  52850. if (this._computeParticleRotation || this.billboard) {
  52851. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52852. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52853. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52854. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52855. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52856. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52857. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52858. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52859. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52860. }
  52861. }
  52862. if (this._particle.translateFromPivot) {
  52863. this._pivotBackTranslation.x = 0.0;
  52864. this._pivotBackTranslation.y = 0.0;
  52865. this._pivotBackTranslation.z = 0.0;
  52866. }
  52867. else {
  52868. this._pivotBackTranslation.x = this._scaledPivot.x;
  52869. this._pivotBackTranslation.y = this._scaledPivot.y;
  52870. this._pivotBackTranslation.z = this._scaledPivot.z;
  52871. }
  52872. // particle vertex loop
  52873. for (pt = 0; pt < this._shape.length; pt++) {
  52874. idx = index + pt * 3;
  52875. colidx = colorIndex + pt * 4;
  52876. uvidx = uvIndex + pt * 2;
  52877. this._vertex.x = this._shape[pt].x;
  52878. this._vertex.y = this._shape[pt].y;
  52879. this._vertex.z = this._shape[pt].z;
  52880. if (this._computeParticleVertex) {
  52881. this.updateParticleVertex(this._particle, this._vertex, pt);
  52882. }
  52883. // positions
  52884. this._vertex.x *= this._particle.scaling.x;
  52885. this._vertex.y *= this._particle.scaling.y;
  52886. this._vertex.z *= this._particle.scaling.z;
  52887. this._vertex.x -= this._scaledPivot.x;
  52888. this._vertex.y -= this._scaledPivot.y;
  52889. this._vertex.z -= this._scaledPivot.z;
  52890. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52891. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52892. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52893. this._rotated.x += this._pivotBackTranslation.x;
  52894. this._rotated.y += this._pivotBackTranslation.y;
  52895. this._rotated.z += this._pivotBackTranslation.z;
  52896. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52897. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52898. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52899. if (this._computeBoundingBox) {
  52900. if (this._positions32[idx] < this._minimum.x) {
  52901. this._minimum.x = this._positions32[idx];
  52902. }
  52903. if (this._positions32[idx] > this._maximum.x) {
  52904. this._maximum.x = this._positions32[idx];
  52905. }
  52906. if (this._positions32[idx + 1] < this._minimum.y) {
  52907. this._minimum.y = this._positions32[idx + 1];
  52908. }
  52909. if (this._positions32[idx + 1] > this._maximum.y) {
  52910. this._maximum.y = this._positions32[idx + 1];
  52911. }
  52912. if (this._positions32[idx + 2] < this._minimum.z) {
  52913. this._minimum.z = this._positions32[idx + 2];
  52914. }
  52915. if (this._positions32[idx + 2] > this._maximum.z) {
  52916. this._maximum.z = this._positions32[idx + 2];
  52917. }
  52918. }
  52919. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52920. if (!this._computeParticleVertex) {
  52921. this._normal.x = this._fixedNormal32[idx];
  52922. this._normal.y = this._fixedNormal32[idx + 1];
  52923. this._normal.z = this._fixedNormal32[idx + 2];
  52924. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52925. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52926. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52927. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52928. 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;
  52929. 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;
  52930. }
  52931. if (this._computeParticleColor && this._particle.color) {
  52932. this._colors32[colidx] = this._particle.color.r;
  52933. this._colors32[colidx + 1] = this._particle.color.g;
  52934. this._colors32[colidx + 2] = this._particle.color.b;
  52935. this._colors32[colidx + 3] = this._particle.color.a;
  52936. }
  52937. if (this._computeParticleTexture) {
  52938. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52939. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52940. }
  52941. }
  52942. }
  52943. else {
  52944. this._particle._stillInvisible = true; // mark the particle as invisible
  52945. for (pt = 0; pt < this._shape.length; pt++) {
  52946. idx = index + pt * 3;
  52947. colidx = colorIndex + pt * 4;
  52948. uvidx = uvIndex + pt * 2;
  52949. this._positions32[idx] = 0.0;
  52950. this._positions32[idx + 1] = 0.0;
  52951. this._positions32[idx + 2] = 0.0;
  52952. this._normals32[idx] = 0.0;
  52953. this._normals32[idx + 1] = 0.0;
  52954. this._normals32[idx + 2] = 0.0;
  52955. if (this._computeParticleColor && this._particle.color) {
  52956. this._colors32[colidx] = this._particle.color.r;
  52957. this._colors32[colidx + 1] = this._particle.color.g;
  52958. this._colors32[colidx + 2] = this._particle.color.b;
  52959. this._colors32[colidx + 3] = this._particle.color.a;
  52960. }
  52961. if (this._computeParticleTexture) {
  52962. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52963. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52964. }
  52965. }
  52966. }
  52967. // if the particle intersections must be computed : update the bbInfo
  52968. if (this._particlesIntersect) {
  52969. var bInfo = this._particle._boundingInfo;
  52970. var bBox = bInfo.boundingBox;
  52971. var bSphere = bInfo.boundingSphere;
  52972. if (!this._bSphereOnly) {
  52973. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52974. for (var b = 0; b < bBox.vectors.length; b++) {
  52975. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52976. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52977. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52978. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52979. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52980. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52981. 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;
  52982. 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;
  52983. 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;
  52984. }
  52985. bBox._update(this.mesh._worldMatrix);
  52986. }
  52987. // place and scale the particle bouding sphere in the SPS local system, then update it
  52988. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52989. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52990. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52991. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52992. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52993. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52994. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52995. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52996. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52997. 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));
  52998. bSphere._update(this.mesh._worldMatrix);
  52999. }
  53000. // increment indexes for the next particle
  53001. index = idx + 3;
  53002. colorIndex = colidx + 4;
  53003. uvIndex = uvidx + 2;
  53004. }
  53005. // if the VBO must be updated
  53006. if (update) {
  53007. if (this._computeParticleColor) {
  53008. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53009. }
  53010. if (this._computeParticleTexture) {
  53011. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53012. }
  53013. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53014. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53015. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53016. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53017. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53018. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53019. for (var i = 0; i < this._normals32.length; i++) {
  53020. this._fixedNormal32[i] = this._normals32[i];
  53021. }
  53022. }
  53023. if (!this.mesh.areNormalsFrozen) {
  53024. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53025. }
  53026. }
  53027. if (this._depthSort && this._depthSortParticles) {
  53028. this.depthSortedParticles.sort(this._depthSortFunction);
  53029. var dspl = this.depthSortedParticles.length;
  53030. var sorted = 0;
  53031. var lind = 0;
  53032. var sind = 0;
  53033. var sid = 0;
  53034. for (sorted = 0; sorted < dspl; sorted++) {
  53035. lind = this.depthSortedParticles[sorted].indicesLength;
  53036. sind = this.depthSortedParticles[sorted].ind;
  53037. for (var i = 0; i < lind; i++) {
  53038. this._indices32[sid] = this._indices[sind + i];
  53039. sid++;
  53040. }
  53041. }
  53042. this.mesh.updateIndices(this._indices32);
  53043. }
  53044. }
  53045. if (this._computeBoundingBox) {
  53046. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53047. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53048. }
  53049. this.afterUpdateParticles(start, end, update);
  53050. return this;
  53051. };
  53052. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53053. this._halfroll = this._roll * 0.5;
  53054. this._halfpitch = this._pitch * 0.5;
  53055. this._halfyaw = this._yaw * 0.5;
  53056. this._sinRoll = Math.sin(this._halfroll);
  53057. this._cosRoll = Math.cos(this._halfroll);
  53058. this._sinPitch = Math.sin(this._halfpitch);
  53059. this._cosPitch = Math.cos(this._halfpitch);
  53060. this._sinYaw = Math.sin(this._halfyaw);
  53061. this._cosYaw = Math.cos(this._halfyaw);
  53062. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53063. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53064. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53065. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53066. };
  53067. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53068. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53069. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53070. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53071. this._rotMatrix.m[3] = 0;
  53072. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53073. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53074. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53075. this._rotMatrix.m[7] = 0;
  53076. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53077. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53078. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53079. this._rotMatrix.m[11] = 0;
  53080. this._rotMatrix.m[12] = 0;
  53081. this._rotMatrix.m[13] = 0;
  53082. this._rotMatrix.m[14] = 0;
  53083. this._rotMatrix.m[15] = 1.0;
  53084. };
  53085. /**
  53086. * Disposes the SPS.
  53087. */
  53088. SolidParticleSystem.prototype.dispose = function () {
  53089. this.mesh.dispose();
  53090. this.vars = null;
  53091. // drop references to internal big arrays for the GC
  53092. this._positions = null;
  53093. this._indices = null;
  53094. this._normals = null;
  53095. this._uvs = null;
  53096. this._colors = null;
  53097. this._indices32 = null;
  53098. this._positions32 = null;
  53099. this._normals32 = null;
  53100. this._fixedNormal32 = null;
  53101. this._uvs32 = null;
  53102. this._colors32 = null;
  53103. this.pickedParticles = null;
  53104. };
  53105. /**
  53106. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53107. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53108. * @returns the SPS.
  53109. */
  53110. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53111. if (!this._isVisibilityBoxLocked) {
  53112. this.mesh.refreshBoundingInfo();
  53113. }
  53114. return this;
  53115. };
  53116. /**
  53117. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53118. * @param size the size (float) of the visibility box
  53119. * note : this doesn't lock the SPS mesh bounding box.
  53120. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53121. */
  53122. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53123. var vis = size / 2;
  53124. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53125. };
  53126. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53127. /**
  53128. * Gets whether the SPS as always visible or not
  53129. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53130. */
  53131. get: function () {
  53132. return this._alwaysVisible;
  53133. },
  53134. /**
  53135. * Sets the SPS as always visible or not
  53136. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53137. */
  53138. set: function (val) {
  53139. this._alwaysVisible = val;
  53140. this.mesh.alwaysSelectAsActiveMesh = val;
  53141. },
  53142. enumerable: true,
  53143. configurable: true
  53144. });
  53145. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53146. /**
  53147. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53148. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53149. */
  53150. get: function () {
  53151. return this._isVisibilityBoxLocked;
  53152. },
  53153. /**
  53154. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53156. */
  53157. set: function (val) {
  53158. this._isVisibilityBoxLocked = val;
  53159. var boundingInfo = this.mesh.getBoundingInfo();
  53160. boundingInfo.isLocked = val;
  53161. },
  53162. enumerable: true,
  53163. configurable: true
  53164. });
  53165. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53166. /**
  53167. * Gets if `setParticles()` computes the particle rotations or not.
  53168. * Default value : true. The SPS is faster when it's set to false.
  53169. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53170. */
  53171. get: function () {
  53172. return this._computeParticleRotation;
  53173. },
  53174. /**
  53175. * Tells to `setParticles()` to compute the particle rotations or not.
  53176. * Default value : true. The SPS is faster when it's set to false.
  53177. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53178. */
  53179. set: function (val) {
  53180. this._computeParticleRotation = val;
  53181. },
  53182. enumerable: true,
  53183. configurable: true
  53184. });
  53185. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53186. /**
  53187. * Gets if `setParticles()` computes the particle colors or not.
  53188. * Default value : true. The SPS is faster when it's set to false.
  53189. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53190. */
  53191. get: function () {
  53192. return this._computeParticleColor;
  53193. },
  53194. /**
  53195. * Tells to `setParticles()` to compute the particle colors or not.
  53196. * Default value : true. The SPS is faster when it's set to false.
  53197. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53198. */
  53199. set: function (val) {
  53200. this._computeParticleColor = val;
  53201. },
  53202. enumerable: true,
  53203. configurable: true
  53204. });
  53205. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53206. /**
  53207. * Gets if `setParticles()` computes the particle textures or not.
  53208. * Default value : true. The SPS is faster when it's set to false.
  53209. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53210. */
  53211. get: function () {
  53212. return this._computeParticleTexture;
  53213. },
  53214. set: function (val) {
  53215. this._computeParticleTexture = val;
  53216. },
  53217. enumerable: true,
  53218. configurable: true
  53219. });
  53220. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53221. /**
  53222. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53223. * Default value : false. The SPS is faster when it's set to false.
  53224. * Note : the particle custom vertex positions aren't stored values.
  53225. */
  53226. get: function () {
  53227. return this._computeParticleVertex;
  53228. },
  53229. /**
  53230. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53231. * Default value : false. The SPS is faster when it's set to false.
  53232. * Note : the particle custom vertex positions aren't stored values.
  53233. */
  53234. set: function (val) {
  53235. this._computeParticleVertex = val;
  53236. },
  53237. enumerable: true,
  53238. configurable: true
  53239. });
  53240. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53241. /**
  53242. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53243. */
  53244. get: function () {
  53245. return this._computeBoundingBox;
  53246. },
  53247. /**
  53248. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53249. */
  53250. set: function (val) {
  53251. this._computeBoundingBox = val;
  53252. },
  53253. enumerable: true,
  53254. configurable: true
  53255. });
  53256. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53257. /**
  53258. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53259. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53260. * Default : `true`
  53261. */
  53262. get: function () {
  53263. return this._depthSortParticles;
  53264. },
  53265. /**
  53266. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53267. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53268. * Default : `true`
  53269. */
  53270. set: function (val) {
  53271. this._depthSortParticles = val;
  53272. },
  53273. enumerable: true,
  53274. configurable: true
  53275. });
  53276. // =======================================================================
  53277. // Particle behavior logic
  53278. // these following methods may be overwritten by the user to fit his needs
  53279. /**
  53280. * This function does nothing. It may be overwritten to set all the particle first values.
  53281. * The SPS doesn't call this function, you may have to call it by your own.
  53282. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53283. */
  53284. SolidParticleSystem.prototype.initParticles = function () {
  53285. };
  53286. /**
  53287. * This function does nothing. It may be overwritten to recycle a particle.
  53288. * The SPS doesn't call this function, you may have to call it by your own.
  53289. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53290. * @param particle The particle to recycle
  53291. * @returns the recycled particle
  53292. */
  53293. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53294. return particle;
  53295. };
  53296. /**
  53297. * Updates a particle : this function should be overwritten by the user.
  53298. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53300. * @example : just set a particle position or velocity and recycle conditions
  53301. * @param particle The particle to update
  53302. * @returns the updated particle
  53303. */
  53304. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53305. return particle;
  53306. };
  53307. /**
  53308. * Updates a vertex of a particle : it can be overwritten by the user.
  53309. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53310. * @param particle the current particle
  53311. * @param vertex the current index of the current particle
  53312. * @param pt the index of the current vertex in the particle shape
  53313. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53314. * @example : just set a vertex particle position
  53315. * @returns the updated vertex
  53316. */
  53317. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53318. return vertex;
  53319. };
  53320. /**
  53321. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53322. * This does nothing and may be overwritten by the user.
  53323. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53324. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53325. * @param update the boolean update value actually passed to setParticles()
  53326. */
  53327. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53328. };
  53329. /**
  53330. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53331. * This will be passed three parameters.
  53332. * This does nothing and may be overwritten by the user.
  53333. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53334. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53335. * @param update the boolean update value actually passed to setParticles()
  53336. */
  53337. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53338. };
  53339. return SolidParticleSystem;
  53340. }());
  53341. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53342. })(BABYLON || (BABYLON = {}));
  53343. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53344. var BABYLON;
  53345. (function (BABYLON) {
  53346. var ShaderMaterial = /** @class */ (function (_super) {
  53347. __extends(ShaderMaterial, _super);
  53348. function ShaderMaterial(name, scene, shaderPath, options) {
  53349. var _this = _super.call(this, name, scene) || this;
  53350. _this._textures = {};
  53351. _this._textureArrays = {};
  53352. _this._floats = {};
  53353. _this._ints = {};
  53354. _this._floatsArrays = {};
  53355. _this._colors3 = {};
  53356. _this._colors3Arrays = {};
  53357. _this._colors4 = {};
  53358. _this._vectors2 = {};
  53359. _this._vectors3 = {};
  53360. _this._vectors4 = {};
  53361. _this._matrices = {};
  53362. _this._matrices3x3 = {};
  53363. _this._matrices2x2 = {};
  53364. _this._vectors2Arrays = {};
  53365. _this._vectors3Arrays = {};
  53366. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53367. _this._shaderPath = shaderPath;
  53368. options.needAlphaBlending = options.needAlphaBlending || false;
  53369. options.needAlphaTesting = options.needAlphaTesting || false;
  53370. options.attributes = options.attributes || ["position", "normal", "uv"];
  53371. options.uniforms = options.uniforms || ["worldViewProjection"];
  53372. options.uniformBuffers = options.uniformBuffers || [];
  53373. options.samplers = options.samplers || [];
  53374. options.defines = options.defines || [];
  53375. _this._options = options;
  53376. return _this;
  53377. }
  53378. ShaderMaterial.prototype.getClassName = function () {
  53379. return "ShaderMaterial";
  53380. };
  53381. ShaderMaterial.prototype.needAlphaBlending = function () {
  53382. return this._options.needAlphaBlending;
  53383. };
  53384. ShaderMaterial.prototype.needAlphaTesting = function () {
  53385. return this._options.needAlphaTesting;
  53386. };
  53387. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53388. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53389. this._options.uniforms.push(uniformName);
  53390. }
  53391. };
  53392. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53393. if (this._options.samplers.indexOf(name) === -1) {
  53394. this._options.samplers.push(name);
  53395. }
  53396. this._textures[name] = texture;
  53397. return this;
  53398. };
  53399. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53400. if (this._options.samplers.indexOf(name) === -1) {
  53401. this._options.samplers.push(name);
  53402. }
  53403. this._checkUniform(name);
  53404. this._textureArrays[name] = textures;
  53405. return this;
  53406. };
  53407. ShaderMaterial.prototype.setFloat = function (name, value) {
  53408. this._checkUniform(name);
  53409. this._floats[name] = value;
  53410. return this;
  53411. };
  53412. ShaderMaterial.prototype.setInt = function (name, value) {
  53413. this._checkUniform(name);
  53414. this._ints[name] = value;
  53415. return this;
  53416. };
  53417. ShaderMaterial.prototype.setFloats = function (name, value) {
  53418. this._checkUniform(name);
  53419. this._floatsArrays[name] = value;
  53420. return this;
  53421. };
  53422. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53423. this._checkUniform(name);
  53424. this._colors3[name] = value;
  53425. return this;
  53426. };
  53427. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53428. this._checkUniform(name);
  53429. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53430. color.toArray(arr, arr.length);
  53431. return arr;
  53432. }, []);
  53433. return this;
  53434. };
  53435. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53436. this._checkUniform(name);
  53437. this._colors4[name] = value;
  53438. return this;
  53439. };
  53440. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53441. this._checkUniform(name);
  53442. this._vectors2[name] = value;
  53443. return this;
  53444. };
  53445. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53446. this._checkUniform(name);
  53447. this._vectors3[name] = value;
  53448. return this;
  53449. };
  53450. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53451. this._checkUniform(name);
  53452. this._vectors4[name] = value;
  53453. return this;
  53454. };
  53455. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53456. this._checkUniform(name);
  53457. this._matrices[name] = value;
  53458. return this;
  53459. };
  53460. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53461. this._checkUniform(name);
  53462. this._matrices3x3[name] = value;
  53463. return this;
  53464. };
  53465. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53466. this._checkUniform(name);
  53467. this._matrices2x2[name] = value;
  53468. return this;
  53469. };
  53470. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53471. this._checkUniform(name);
  53472. this._vectors2Arrays[name] = value;
  53473. return this;
  53474. };
  53475. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53476. this._checkUniform(name);
  53477. this._vectors3Arrays[name] = value;
  53478. return this;
  53479. };
  53480. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53481. if (!mesh) {
  53482. return true;
  53483. }
  53484. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53485. return false;
  53486. }
  53487. return false;
  53488. };
  53489. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53490. var scene = this.getScene();
  53491. var engine = scene.getEngine();
  53492. if (!this.checkReadyOnEveryCall) {
  53493. if (this._renderId === scene.getRenderId()) {
  53494. if (this._checkCache(scene, mesh, useInstances)) {
  53495. return true;
  53496. }
  53497. }
  53498. }
  53499. // Instances
  53500. var defines = [];
  53501. var attribs = [];
  53502. var fallbacks = new BABYLON.EffectFallbacks();
  53503. if (useInstances) {
  53504. defines.push("#define INSTANCES");
  53505. }
  53506. for (var index = 0; index < this._options.defines.length; index++) {
  53507. defines.push(this._options.defines[index]);
  53508. }
  53509. for (var index = 0; index < this._options.attributes.length; index++) {
  53510. attribs.push(this._options.attributes[index]);
  53511. }
  53512. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53513. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53514. defines.push("#define VERTEXCOLOR");
  53515. }
  53516. // Bones
  53517. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53520. if (mesh.numBoneInfluencers > 4) {
  53521. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53522. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53523. }
  53524. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53526. fallbacks.addCPUSkinningFallback(0, mesh);
  53527. if (this._options.uniforms.indexOf("mBones") === -1) {
  53528. this._options.uniforms.push("mBones");
  53529. }
  53530. }
  53531. else {
  53532. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53533. }
  53534. // Textures
  53535. for (var name in this._textures) {
  53536. if (!this._textures[name].isReady()) {
  53537. return false;
  53538. }
  53539. }
  53540. // Alpha test
  53541. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53542. defines.push("#define ALPHATEST");
  53543. }
  53544. var previousEffect = this._effect;
  53545. var join = defines.join("\n");
  53546. this._effect = engine.createEffect(this._shaderPath, {
  53547. attributes: attribs,
  53548. uniformsNames: this._options.uniforms,
  53549. uniformBuffersNames: this._options.uniformBuffers,
  53550. samplers: this._options.samplers,
  53551. defines: join,
  53552. fallbacks: fallbacks,
  53553. onCompiled: this.onCompiled,
  53554. onError: this.onError
  53555. }, engine);
  53556. if (!this._effect.isReady()) {
  53557. return false;
  53558. }
  53559. if (previousEffect !== this._effect) {
  53560. scene.resetCachedMaterial();
  53561. }
  53562. this._renderId = scene.getRenderId();
  53563. return true;
  53564. };
  53565. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53566. var scene = this.getScene();
  53567. if (!this._effect) {
  53568. return;
  53569. }
  53570. if (this._options.uniforms.indexOf("world") !== -1) {
  53571. this._effect.setMatrix("world", world);
  53572. }
  53573. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53574. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53575. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53576. }
  53577. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53578. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53579. }
  53580. };
  53581. ShaderMaterial.prototype.bind = function (world, mesh) {
  53582. // Std values
  53583. this.bindOnlyWorldMatrix(world);
  53584. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53585. if (this._options.uniforms.indexOf("view") !== -1) {
  53586. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53587. }
  53588. if (this._options.uniforms.indexOf("projection") !== -1) {
  53589. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53590. }
  53591. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53592. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53593. }
  53594. // Bones
  53595. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53596. var name;
  53597. // Texture
  53598. for (name in this._textures) {
  53599. this._effect.setTexture(name, this._textures[name]);
  53600. }
  53601. // Texture arrays
  53602. for (name in this._textureArrays) {
  53603. this._effect.setTextureArray(name, this._textureArrays[name]);
  53604. }
  53605. // Int
  53606. for (name in this._ints) {
  53607. this._effect.setInt(name, this._ints[name]);
  53608. }
  53609. // Float
  53610. for (name in this._floats) {
  53611. this._effect.setFloat(name, this._floats[name]);
  53612. }
  53613. // Floats
  53614. for (name in this._floatsArrays) {
  53615. this._effect.setArray(name, this._floatsArrays[name]);
  53616. }
  53617. // Color3
  53618. for (name in this._colors3) {
  53619. this._effect.setColor3(name, this._colors3[name]);
  53620. }
  53621. for (name in this._colors3Arrays) {
  53622. this._effect.setArray3(name, this._colors3Arrays[name]);
  53623. }
  53624. // Color4
  53625. for (name in this._colors4) {
  53626. var color = this._colors4[name];
  53627. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53628. }
  53629. // Vector2
  53630. for (name in this._vectors2) {
  53631. this._effect.setVector2(name, this._vectors2[name]);
  53632. }
  53633. // Vector3
  53634. for (name in this._vectors3) {
  53635. this._effect.setVector3(name, this._vectors3[name]);
  53636. }
  53637. // Vector4
  53638. for (name in this._vectors4) {
  53639. this._effect.setVector4(name, this._vectors4[name]);
  53640. }
  53641. // Matrix
  53642. for (name in this._matrices) {
  53643. this._effect.setMatrix(name, this._matrices[name]);
  53644. }
  53645. // Matrix 3x3
  53646. for (name in this._matrices3x3) {
  53647. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53648. }
  53649. // Matrix 2x2
  53650. for (name in this._matrices2x2) {
  53651. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53652. }
  53653. // Vector2Array
  53654. for (name in this._vectors2Arrays) {
  53655. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53656. }
  53657. // Vector3Array
  53658. for (name in this._vectors3Arrays) {
  53659. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53660. }
  53661. }
  53662. this._afterBind(mesh);
  53663. };
  53664. ShaderMaterial.prototype.getActiveTextures = function () {
  53665. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53666. for (var name in this._textures) {
  53667. activeTextures.push(this._textures[name]);
  53668. }
  53669. for (var name in this._textureArrays) {
  53670. var array = this._textureArrays[name];
  53671. for (var index = 0; index < array.length; index++) {
  53672. activeTextures.push(array[index]);
  53673. }
  53674. }
  53675. return activeTextures;
  53676. };
  53677. ShaderMaterial.prototype.hasTexture = function (texture) {
  53678. if (_super.prototype.hasTexture.call(this, texture)) {
  53679. return true;
  53680. }
  53681. for (var name in this._textures) {
  53682. if (this._textures[name] === texture) {
  53683. return true;
  53684. }
  53685. }
  53686. for (var name in this._textureArrays) {
  53687. var array = this._textureArrays[name];
  53688. for (var index = 0; index < array.length; index++) {
  53689. if (array[index] === texture) {
  53690. return true;
  53691. }
  53692. }
  53693. }
  53694. return false;
  53695. };
  53696. ShaderMaterial.prototype.clone = function (name) {
  53697. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53698. return newShaderMaterial;
  53699. };
  53700. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53701. if (forceDisposeTextures) {
  53702. var name;
  53703. for (name in this._textures) {
  53704. this._textures[name].dispose();
  53705. }
  53706. for (name in this._textureArrays) {
  53707. var array = this._textureArrays[name];
  53708. for (var index = 0; index < array.length; index++) {
  53709. array[index].dispose();
  53710. }
  53711. }
  53712. }
  53713. this._textures = {};
  53714. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53715. };
  53716. ShaderMaterial.prototype.serialize = function () {
  53717. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53718. serializationObject.customType = "BABYLON.ShaderMaterial";
  53719. serializationObject.options = this._options;
  53720. serializationObject.shaderPath = this._shaderPath;
  53721. var name;
  53722. // Texture
  53723. serializationObject.textures = {};
  53724. for (name in this._textures) {
  53725. serializationObject.textures[name] = this._textures[name].serialize();
  53726. }
  53727. // Texture arrays
  53728. serializationObject.textureArrays = {};
  53729. for (name in this._textureArrays) {
  53730. serializationObject.textureArrays[name] = [];
  53731. var array = this._textureArrays[name];
  53732. for (var index = 0; index < array.length; index++) {
  53733. serializationObject.textureArrays[name].push(array[index].serialize());
  53734. }
  53735. }
  53736. // Float
  53737. serializationObject.floats = {};
  53738. for (name in this._floats) {
  53739. serializationObject.floats[name] = this._floats[name];
  53740. }
  53741. // Float s
  53742. serializationObject.FloatArrays = {};
  53743. for (name in this._floatsArrays) {
  53744. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53745. }
  53746. // Color3
  53747. serializationObject.colors3 = {};
  53748. for (name in this._colors3) {
  53749. serializationObject.colors3[name] = this._colors3[name].asArray();
  53750. }
  53751. // Color3 array
  53752. serializationObject.colors3Arrays = {};
  53753. for (name in this._colors3Arrays) {
  53754. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53755. }
  53756. // Color4
  53757. serializationObject.colors4 = {};
  53758. for (name in this._colors4) {
  53759. serializationObject.colors4[name] = this._colors4[name].asArray();
  53760. }
  53761. // Vector2
  53762. serializationObject.vectors2 = {};
  53763. for (name in this._vectors2) {
  53764. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53765. }
  53766. // Vector3
  53767. serializationObject.vectors3 = {};
  53768. for (name in this._vectors3) {
  53769. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53770. }
  53771. // Vector4
  53772. serializationObject.vectors4 = {};
  53773. for (name in this._vectors4) {
  53774. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53775. }
  53776. // Matrix
  53777. serializationObject.matrices = {};
  53778. for (name in this._matrices) {
  53779. serializationObject.matrices[name] = this._matrices[name].asArray();
  53780. }
  53781. // Matrix 3x3
  53782. serializationObject.matrices3x3 = {};
  53783. for (name in this._matrices3x3) {
  53784. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53785. }
  53786. // Matrix 2x2
  53787. serializationObject.matrices2x2 = {};
  53788. for (name in this._matrices2x2) {
  53789. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53790. }
  53791. // Vector2Array
  53792. serializationObject.vectors2Arrays = {};
  53793. for (name in this._vectors2Arrays) {
  53794. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53795. }
  53796. // Vector3Array
  53797. serializationObject.vectors3Arrays = {};
  53798. for (name in this._vectors3Arrays) {
  53799. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53800. }
  53801. return serializationObject;
  53802. };
  53803. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53804. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53805. var name;
  53806. // Texture
  53807. for (name in source.textures) {
  53808. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53809. }
  53810. // Texture arrays
  53811. for (name in source.textureArrays) {
  53812. var array = source.textureArrays[name];
  53813. var textureArray = new Array();
  53814. for (var index = 0; index < array.length; index++) {
  53815. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53816. }
  53817. material.setTextureArray(name, textureArray);
  53818. }
  53819. // Float
  53820. for (name in source.floats) {
  53821. material.setFloat(name, source.floats[name]);
  53822. }
  53823. // Float s
  53824. for (name in source.floatsArrays) {
  53825. material.setFloats(name, source.floatsArrays[name]);
  53826. }
  53827. // Color3
  53828. for (name in source.colors3) {
  53829. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53830. }
  53831. // Color3 arrays
  53832. for (name in source.colors3Arrays) {
  53833. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53834. if (i % 3 === 0) {
  53835. arr.push([num]);
  53836. }
  53837. else {
  53838. arr[arr.length - 1].push(num);
  53839. }
  53840. return arr;
  53841. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53842. material.setColor3Array(name, colors);
  53843. }
  53844. // Color4
  53845. for (name in source.colors4) {
  53846. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53847. }
  53848. // Vector2
  53849. for (name in source.vectors2) {
  53850. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53851. }
  53852. // Vector3
  53853. for (name in source.vectors3) {
  53854. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53855. }
  53856. // Vector4
  53857. for (name in source.vectors4) {
  53858. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53859. }
  53860. // Matrix
  53861. for (name in source.matrices) {
  53862. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53863. }
  53864. // Matrix 3x3
  53865. for (name in source.matrices3x3) {
  53866. material.setMatrix3x3(name, source.matrices3x3[name]);
  53867. }
  53868. // Matrix 2x2
  53869. for (name in source.matrices2x2) {
  53870. material.setMatrix2x2(name, source.matrices2x2[name]);
  53871. }
  53872. // Vector2Array
  53873. for (name in source.vectors2Arrays) {
  53874. material.setArray2(name, source.vectors2Arrays[name]);
  53875. }
  53876. // Vector3Array
  53877. for (name in source.vectors3Arrays) {
  53878. material.setArray3(name, source.vectors3Arrays[name]);
  53879. }
  53880. return material;
  53881. };
  53882. return ShaderMaterial;
  53883. }(BABYLON.Material));
  53884. BABYLON.ShaderMaterial = ShaderMaterial;
  53885. })(BABYLON || (BABYLON = {}));
  53886. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53887. var BABYLON;
  53888. (function (BABYLON) {
  53889. var GroundMesh = /** @class */ (function (_super) {
  53890. __extends(GroundMesh, _super);
  53891. function GroundMesh(name, scene) {
  53892. var _this = _super.call(this, name, scene) || this;
  53893. _this.generateOctree = false;
  53894. return _this;
  53895. }
  53896. GroundMesh.prototype.getClassName = function () {
  53897. return "GroundMesh";
  53898. };
  53899. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53900. get: function () {
  53901. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53902. },
  53903. enumerable: true,
  53904. configurable: true
  53905. });
  53906. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53907. get: function () {
  53908. return this._subdivisionsX;
  53909. },
  53910. enumerable: true,
  53911. configurable: true
  53912. });
  53913. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53914. get: function () {
  53915. return this._subdivisionsY;
  53916. },
  53917. enumerable: true,
  53918. configurable: true
  53919. });
  53920. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53921. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53922. this._subdivisionsX = chunksCount;
  53923. this._subdivisionsY = chunksCount;
  53924. this.subdivide(chunksCount);
  53925. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53926. };
  53927. /**
  53928. * Returns a height (y) value in the Worl system :
  53929. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53930. * Returns the ground y position if (x, z) are outside the ground surface.
  53931. */
  53932. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53933. var world = this.getWorldMatrix();
  53934. var invMat = BABYLON.Tmp.Matrix[5];
  53935. world.invertToRef(invMat);
  53936. var tmpVect = BABYLON.Tmp.Vector3[8];
  53937. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53938. x = tmpVect.x;
  53939. z = tmpVect.z;
  53940. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53941. return this.position.y;
  53942. }
  53943. if (!this._heightQuads || this._heightQuads.length == 0) {
  53944. this._initHeightQuads();
  53945. this._computeHeightQuads();
  53946. }
  53947. var facet = this._getFacetAt(x, z);
  53948. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53949. // return y in the World system
  53950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53951. return tmpVect.y;
  53952. };
  53953. /**
  53954. * Returns a normalized vector (Vector3) orthogonal to the ground
  53955. * at the ground coordinates (x, z) expressed in the World system.
  53956. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53957. */
  53958. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53959. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53960. this.getNormalAtCoordinatesToRef(x, z, normal);
  53961. return normal;
  53962. };
  53963. /**
  53964. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53965. * at the ground coordinates (x, z) expressed in the World system.
  53966. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53967. * Returns the GroundMesh.
  53968. */
  53969. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53970. var world = this.getWorldMatrix();
  53971. var tmpMat = BABYLON.Tmp.Matrix[5];
  53972. world.invertToRef(tmpMat);
  53973. var tmpVect = BABYLON.Tmp.Vector3[8];
  53974. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53975. x = tmpVect.x;
  53976. z = tmpVect.z;
  53977. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53978. return this;
  53979. }
  53980. if (!this._heightQuads || this._heightQuads.length == 0) {
  53981. this._initHeightQuads();
  53982. this._computeHeightQuads();
  53983. }
  53984. var facet = this._getFacetAt(x, z);
  53985. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53986. return this;
  53987. };
  53988. /**
  53989. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53990. * if the ground has been updated.
  53991. * This can be used in the render loop.
  53992. * Returns the GroundMesh.
  53993. */
  53994. GroundMesh.prototype.updateCoordinateHeights = function () {
  53995. if (!this._heightQuads || this._heightQuads.length == 0) {
  53996. this._initHeightQuads();
  53997. }
  53998. this._computeHeightQuads();
  53999. return this;
  54000. };
  54001. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54002. GroundMesh.prototype._getFacetAt = function (x, z) {
  54003. // retrieve col and row from x, z coordinates in the ground local system
  54004. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54005. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54006. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54007. var facet;
  54008. if (z < quad.slope.x * x + quad.slope.y) {
  54009. facet = quad.facet1;
  54010. }
  54011. else {
  54012. facet = quad.facet2;
  54013. }
  54014. return facet;
  54015. };
  54016. // Creates and populates the heightMap array with "facet" elements :
  54017. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54018. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54019. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54020. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54021. // Returns the GroundMesh.
  54022. GroundMesh.prototype._initHeightQuads = function () {
  54023. var subdivisionsX = this._subdivisionsX;
  54024. var subdivisionsY = this._subdivisionsY;
  54025. this._heightQuads = new Array();
  54026. for (var row = 0; row < subdivisionsY; row++) {
  54027. for (var col = 0; col < subdivisionsX; col++) {
  54028. 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) };
  54029. this._heightQuads[row * subdivisionsX + col] = quad;
  54030. }
  54031. }
  54032. return this;
  54033. };
  54034. // Compute each quad element values and update the the heightMap array :
  54035. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54036. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54037. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54038. // Returns the GroundMesh.
  54039. GroundMesh.prototype._computeHeightQuads = function () {
  54040. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54041. if (!positions) {
  54042. return this;
  54043. }
  54044. var v1 = BABYLON.Tmp.Vector3[3];
  54045. var v2 = BABYLON.Tmp.Vector3[2];
  54046. var v3 = BABYLON.Tmp.Vector3[1];
  54047. var v4 = BABYLON.Tmp.Vector3[0];
  54048. var v1v2 = BABYLON.Tmp.Vector3[4];
  54049. var v1v3 = BABYLON.Tmp.Vector3[5];
  54050. var v1v4 = BABYLON.Tmp.Vector3[6];
  54051. var norm1 = BABYLON.Tmp.Vector3[7];
  54052. var norm2 = BABYLON.Tmp.Vector3[8];
  54053. var i = 0;
  54054. var j = 0;
  54055. var k = 0;
  54056. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54057. var h = 0;
  54058. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54059. var d2 = 0;
  54060. var subdivisionsX = this._subdivisionsX;
  54061. var subdivisionsY = this._subdivisionsY;
  54062. for (var row = 0; row < subdivisionsY; row++) {
  54063. for (var col = 0; col < subdivisionsX; col++) {
  54064. i = col * 3;
  54065. j = row * (subdivisionsX + 1) * 3;
  54066. k = (row + 1) * (subdivisionsX + 1) * 3;
  54067. v1.x = positions[j + i];
  54068. v1.y = positions[j + i + 1];
  54069. v1.z = positions[j + i + 2];
  54070. v2.x = positions[j + i + 3];
  54071. v2.y = positions[j + i + 4];
  54072. v2.z = positions[j + i + 5];
  54073. v3.x = positions[k + i];
  54074. v3.y = positions[k + i + 1];
  54075. v3.z = positions[k + i + 2];
  54076. v4.x = positions[k + i + 3];
  54077. v4.y = positions[k + i + 4];
  54078. v4.z = positions[k + i + 5];
  54079. // 2D slope V1V4
  54080. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54081. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54082. // facet equations :
  54083. // we compute each facet normal vector
  54084. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54085. // we compute the value d by applying the equation to v1 which belongs to the plane
  54086. // then we store the facet equation in a Vector4
  54087. v2.subtractToRef(v1, v1v2);
  54088. v3.subtractToRef(v1, v1v3);
  54089. v4.subtractToRef(v1, v1v4);
  54090. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54091. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54092. norm1.normalize();
  54093. norm2.normalize();
  54094. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54095. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54096. var quad = this._heightQuads[row * subdivisionsX + col];
  54097. quad.slope.copyFromFloats(cd, h);
  54098. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54099. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54100. }
  54101. }
  54102. return this;
  54103. };
  54104. GroundMesh.prototype.serialize = function (serializationObject) {
  54105. _super.prototype.serialize.call(this, serializationObject);
  54106. serializationObject.subdivisionsX = this._subdivisionsX;
  54107. serializationObject.subdivisionsY = this._subdivisionsY;
  54108. serializationObject.minX = this._minX;
  54109. serializationObject.maxX = this._maxX;
  54110. serializationObject.minZ = this._minZ;
  54111. serializationObject.maxZ = this._maxZ;
  54112. serializationObject.width = this._width;
  54113. serializationObject.height = this._height;
  54114. };
  54115. GroundMesh.Parse = function (parsedMesh, scene) {
  54116. var result = new GroundMesh(parsedMesh.name, scene);
  54117. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54118. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54119. result._minX = parsedMesh.minX;
  54120. result._maxX = parsedMesh.maxX;
  54121. result._minZ = parsedMesh.minZ;
  54122. result._maxZ = parsedMesh.maxZ;
  54123. result._width = parsedMesh.width;
  54124. result._height = parsedMesh.height;
  54125. return result;
  54126. };
  54127. return GroundMesh;
  54128. }(BABYLON.Mesh));
  54129. BABYLON.GroundMesh = GroundMesh;
  54130. })(BABYLON || (BABYLON = {}));
  54131. //# sourceMappingURL=babylon.groundMesh.js.map
  54132. var BABYLON;
  54133. (function (BABYLON) {
  54134. /**
  54135. * Creates an instance based on a source mesh.
  54136. */
  54137. var InstancedMesh = /** @class */ (function (_super) {
  54138. __extends(InstancedMesh, _super);
  54139. function InstancedMesh(name, source) {
  54140. var _this = _super.call(this, name, source.getScene()) || this;
  54141. source.instances.push(_this);
  54142. _this._sourceMesh = source;
  54143. _this.position.copyFrom(source.position);
  54144. _this.rotation.copyFrom(source.rotation);
  54145. _this.scaling.copyFrom(source.scaling);
  54146. if (source.rotationQuaternion) {
  54147. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54148. }
  54149. _this.infiniteDistance = source.infiniteDistance;
  54150. _this.setPivotMatrix(source.getPivotMatrix());
  54151. _this.refreshBoundingInfo();
  54152. _this._syncSubMeshes();
  54153. return _this;
  54154. }
  54155. /**
  54156. * Returns the string "InstancedMesh".
  54157. */
  54158. InstancedMesh.prototype.getClassName = function () {
  54159. return "InstancedMesh";
  54160. };
  54161. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54162. // Methods
  54163. get: function () {
  54164. return this._sourceMesh.receiveShadows;
  54165. },
  54166. enumerable: true,
  54167. configurable: true
  54168. });
  54169. Object.defineProperty(InstancedMesh.prototype, "material", {
  54170. get: function () {
  54171. return this._sourceMesh.material;
  54172. },
  54173. enumerable: true,
  54174. configurable: true
  54175. });
  54176. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54177. get: function () {
  54178. return this._sourceMesh.visibility;
  54179. },
  54180. enumerable: true,
  54181. configurable: true
  54182. });
  54183. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54184. get: function () {
  54185. return this._sourceMesh.skeleton;
  54186. },
  54187. enumerable: true,
  54188. configurable: true
  54189. });
  54190. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54191. get: function () {
  54192. return this._sourceMesh.renderingGroupId;
  54193. },
  54194. enumerable: true,
  54195. configurable: true
  54196. });
  54197. /**
  54198. * Returns the total number of vertices (integer).
  54199. */
  54200. InstancedMesh.prototype.getTotalVertices = function () {
  54201. return this._sourceMesh.getTotalVertices();
  54202. };
  54203. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54204. get: function () {
  54205. return this._sourceMesh;
  54206. },
  54207. enumerable: true,
  54208. configurable: true
  54209. });
  54210. /**
  54211. * Is this node ready to be used/rendered
  54212. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54213. * @return {boolean} is it ready
  54214. */
  54215. InstancedMesh.prototype.isReady = function (completeCheck) {
  54216. if (completeCheck === void 0) { completeCheck = false; }
  54217. return this._sourceMesh.isReady(completeCheck, true);
  54218. };
  54219. /**
  54220. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54221. */
  54222. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54223. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54224. };
  54225. /**
  54226. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54227. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54228. * The `data` are either a numeric array either a Float32Array.
  54229. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54230. * 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).
  54231. * Note that a new underlying VertexBuffer object is created each call.
  54232. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54233. *
  54234. * Possible `kind` values :
  54235. * - BABYLON.VertexBuffer.PositionKind
  54236. * - BABYLON.VertexBuffer.UVKind
  54237. * - BABYLON.VertexBuffer.UV2Kind
  54238. * - BABYLON.VertexBuffer.UV3Kind
  54239. * - BABYLON.VertexBuffer.UV4Kind
  54240. * - BABYLON.VertexBuffer.UV5Kind
  54241. * - BABYLON.VertexBuffer.UV6Kind
  54242. * - BABYLON.VertexBuffer.ColorKind
  54243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54247. *
  54248. * Returns the Mesh.
  54249. */
  54250. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54251. if (this.sourceMesh) {
  54252. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54253. }
  54254. return this.sourceMesh;
  54255. };
  54256. /**
  54257. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54258. * If the mesh has no geometry, it is simply returned as it is.
  54259. * The `data` are either a numeric array either a Float32Array.
  54260. * No new underlying VertexBuffer object is created.
  54261. * 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.
  54262. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54263. *
  54264. * Possible `kind` values :
  54265. * - BABYLON.VertexBuffer.PositionKind
  54266. * - BABYLON.VertexBuffer.UVKind
  54267. * - BABYLON.VertexBuffer.UV2Kind
  54268. * - BABYLON.VertexBuffer.UV3Kind
  54269. * - BABYLON.VertexBuffer.UV4Kind
  54270. * - BABYLON.VertexBuffer.UV5Kind
  54271. * - BABYLON.VertexBuffer.UV6Kind
  54272. * - BABYLON.VertexBuffer.ColorKind
  54273. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54274. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54275. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54276. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54277. *
  54278. * Returns the Mesh.
  54279. */
  54280. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54281. if (this.sourceMesh) {
  54282. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54283. }
  54284. return this.sourceMesh;
  54285. };
  54286. /**
  54287. * Sets the mesh indices.
  54288. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54289. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54290. * This method creates a new index buffer each call.
  54291. * Returns the Mesh.
  54292. */
  54293. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54294. if (totalVertices === void 0) { totalVertices = null; }
  54295. if (this.sourceMesh) {
  54296. this.sourceMesh.setIndices(indices, totalVertices);
  54297. }
  54298. return this.sourceMesh;
  54299. };
  54300. /**
  54301. * Boolean : True if the mesh owns the requested kind of data.
  54302. */
  54303. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54304. return this._sourceMesh.isVerticesDataPresent(kind);
  54305. };
  54306. /**
  54307. * Returns an array of indices (IndicesArray).
  54308. */
  54309. InstancedMesh.prototype.getIndices = function () {
  54310. return this._sourceMesh.getIndices();
  54311. };
  54312. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54313. get: function () {
  54314. return this._sourceMesh._positions;
  54315. },
  54316. enumerable: true,
  54317. configurable: true
  54318. });
  54319. /**
  54320. * Sets a new updated BoundingInfo to the mesh.
  54321. * Returns the mesh.
  54322. */
  54323. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54324. var meshBB = this._sourceMesh.getBoundingInfo();
  54325. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54326. this._updateBoundingInfo();
  54327. return this;
  54328. };
  54329. InstancedMesh.prototype._preActivate = function () {
  54330. if (this._currentLOD) {
  54331. this._currentLOD._preActivate();
  54332. }
  54333. return this;
  54334. };
  54335. InstancedMesh.prototype._activate = function (renderId) {
  54336. if (this._currentLOD) {
  54337. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54338. }
  54339. return this;
  54340. };
  54341. /**
  54342. * Returns the current associated LOD AbstractMesh.
  54343. */
  54344. InstancedMesh.prototype.getLOD = function (camera) {
  54345. if (!camera) {
  54346. return this;
  54347. }
  54348. var boundingInfo = this.getBoundingInfo();
  54349. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54350. if (this._currentLOD === this.sourceMesh) {
  54351. return this;
  54352. }
  54353. return this._currentLOD;
  54354. };
  54355. InstancedMesh.prototype._syncSubMeshes = function () {
  54356. this.releaseSubMeshes();
  54357. if (this._sourceMesh.subMeshes) {
  54358. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54359. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54360. }
  54361. }
  54362. return this;
  54363. };
  54364. InstancedMesh.prototype._generatePointsArray = function () {
  54365. return this._sourceMesh._generatePointsArray();
  54366. };
  54367. /**
  54368. * Creates a new InstancedMesh from the current mesh.
  54369. * - name (string) : the cloned mesh name
  54370. * - newParent (optional Node) : the optional Node to parent the clone to.
  54371. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54372. *
  54373. * Returns the clone.
  54374. */
  54375. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54376. var result = this._sourceMesh.createInstance(name);
  54377. // Deep copy
  54378. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54379. // Bounding info
  54380. this.refreshBoundingInfo();
  54381. // Parent
  54382. if (newParent) {
  54383. result.parent = newParent;
  54384. }
  54385. if (!doNotCloneChildren) {
  54386. // Children
  54387. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54388. var mesh = this.getScene().meshes[index];
  54389. if (mesh.parent === this) {
  54390. mesh.clone(mesh.name, result);
  54391. }
  54392. }
  54393. }
  54394. result.computeWorldMatrix(true);
  54395. return result;
  54396. };
  54397. /**
  54398. * Disposes the InstancedMesh.
  54399. * Returns nothing.
  54400. */
  54401. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54402. // Remove from mesh
  54403. var index = this._sourceMesh.instances.indexOf(this);
  54404. this._sourceMesh.instances.splice(index, 1);
  54405. _super.prototype.dispose.call(this, doNotRecurse);
  54406. };
  54407. return InstancedMesh;
  54408. }(BABYLON.AbstractMesh));
  54409. BABYLON.InstancedMesh = InstancedMesh;
  54410. })(BABYLON || (BABYLON = {}));
  54411. //# sourceMappingURL=babylon.instancedMesh.js.map
  54412. var BABYLON;
  54413. (function (BABYLON) {
  54414. var LinesMesh = /** @class */ (function (_super) {
  54415. __extends(LinesMesh, _super);
  54416. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54417. if (scene === void 0) { scene = null; }
  54418. if (parent === void 0) { parent = null; }
  54419. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54420. _this.useVertexColor = useVertexColor;
  54421. _this.useVertexAlpha = useVertexAlpha;
  54422. _this.color = new BABYLON.Color3(1, 1, 1);
  54423. _this.alpha = 1;
  54424. if (source) {
  54425. _this.color = source.color.clone();
  54426. _this.alpha = source.alpha;
  54427. _this.useVertexColor = source.useVertexColor;
  54428. _this.useVertexAlpha = source.useVertexAlpha;
  54429. }
  54430. _this._intersectionThreshold = 0.1;
  54431. var defines = [];
  54432. var options = {
  54433. attributes: [BABYLON.VertexBuffer.PositionKind],
  54434. uniforms: ["world", "viewProjection"],
  54435. needAlphaBlending: true,
  54436. defines: defines
  54437. };
  54438. if (useVertexAlpha === false) {
  54439. options.needAlphaBlending = false;
  54440. }
  54441. if (!useVertexColor) {
  54442. options.uniforms.push("color");
  54443. }
  54444. else {
  54445. options.defines.push("#define VERTEXCOLOR");
  54446. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54447. }
  54448. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54449. return _this;
  54450. }
  54451. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54452. /**
  54453. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54454. * This margin is expressed in world space coordinates, so its value may vary.
  54455. * Default value is 0.1
  54456. * @returns the intersection Threshold value.
  54457. */
  54458. get: function () {
  54459. return this._intersectionThreshold;
  54460. },
  54461. /**
  54462. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54463. * This margin is expressed in world space coordinates, so its value may vary.
  54464. * @param value the new threshold to apply
  54465. */
  54466. set: function (value) {
  54467. if (this._intersectionThreshold === value) {
  54468. return;
  54469. }
  54470. this._intersectionThreshold = value;
  54471. if (this.geometry) {
  54472. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54473. }
  54474. },
  54475. enumerable: true,
  54476. configurable: true
  54477. });
  54478. /**
  54479. * Returns the string "LineMesh"
  54480. */
  54481. LinesMesh.prototype.getClassName = function () {
  54482. return "LinesMesh";
  54483. };
  54484. Object.defineProperty(LinesMesh.prototype, "material", {
  54485. get: function () {
  54486. return this._colorShader;
  54487. },
  54488. set: function (value) {
  54489. // Do nothing
  54490. },
  54491. enumerable: true,
  54492. configurable: true
  54493. });
  54494. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54495. get: function () {
  54496. return false;
  54497. },
  54498. enumerable: true,
  54499. configurable: true
  54500. });
  54501. LinesMesh.prototype.createInstance = function (name) {
  54502. throw new Error("LinesMeshes do not support createInstance.");
  54503. };
  54504. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54505. if (!this._geometry) {
  54506. return this;
  54507. }
  54508. // VBOs
  54509. this._geometry._bind(this._colorShader.getEffect());
  54510. // Color
  54511. if (!this.useVertexColor) {
  54512. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54513. }
  54514. return this;
  54515. };
  54516. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54517. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54518. return this;
  54519. }
  54520. var engine = this.getScene().getEngine();
  54521. // Draw order
  54522. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54523. return this;
  54524. };
  54525. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54526. this._colorShader.dispose();
  54527. _super.prototype.dispose.call(this, doNotRecurse);
  54528. };
  54529. /**
  54530. * Returns a new LineMesh object cloned from the current one.
  54531. */
  54532. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54533. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54534. };
  54535. return LinesMesh;
  54536. }(BABYLON.Mesh));
  54537. BABYLON.LinesMesh = LinesMesh;
  54538. })(BABYLON || (BABYLON = {}));
  54539. //# sourceMappingURL=babylon.linesMesh.js.map
  54540. var BABYLON;
  54541. (function (BABYLON) {
  54542. var MeshBuilder = /** @class */ (function () {
  54543. function MeshBuilder() {
  54544. }
  54545. MeshBuilder.updateSideOrientation = function (orientation) {
  54546. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54547. return BABYLON.Mesh.DOUBLESIDE;
  54548. }
  54549. if (orientation === undefined || orientation === null) {
  54550. return BABYLON.Mesh.FRONTSIDE;
  54551. }
  54552. return orientation;
  54553. };
  54554. /**
  54555. * Creates a box mesh.
  54556. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54557. * The parameter `size` sets the size (float) of each box side (default 1).
  54558. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54559. * 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).
  54560. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54562. * 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).
  54563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54565. */
  54566. MeshBuilder.CreateBox = function (name, options, scene) {
  54567. if (scene === void 0) { scene = null; }
  54568. var box = new BABYLON.Mesh(name, scene);
  54569. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54570. box._originalBuilderSideOrientation = options.sideOrientation;
  54571. var vertexData = BABYLON.VertexData.CreateBox(options);
  54572. vertexData.applyToMesh(box, options.updatable);
  54573. return box;
  54574. };
  54575. /**
  54576. * Creates a sphere mesh.
  54577. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54578. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54579. * 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`).
  54580. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54581. * 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
  54582. * 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).
  54583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54584. * 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).
  54585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54587. */
  54588. MeshBuilder.CreateSphere = function (name, options, scene) {
  54589. var sphere = new BABYLON.Mesh(name, scene);
  54590. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54591. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54592. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54593. vertexData.applyToMesh(sphere, options.updatable);
  54594. return sphere;
  54595. };
  54596. /**
  54597. * Creates a plane polygonal mesh. By default, this is a disc.
  54598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54599. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54600. * 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.
  54601. * 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
  54602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54603. * 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).
  54604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54606. */
  54607. MeshBuilder.CreateDisc = function (name, options, scene) {
  54608. if (scene === void 0) { scene = null; }
  54609. var disc = new BABYLON.Mesh(name, scene);
  54610. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54611. disc._originalBuilderSideOrientation = options.sideOrientation;
  54612. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54613. vertexData.applyToMesh(disc, options.updatable);
  54614. return disc;
  54615. };
  54616. /**
  54617. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54619. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54620. * 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`).
  54621. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54622. * 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.
  54623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54624. * 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).
  54625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54627. */
  54628. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54629. var sphere = new BABYLON.Mesh(name, scene);
  54630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54631. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54632. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54633. vertexData.applyToMesh(sphere, options.updatable);
  54634. return sphere;
  54635. };
  54636. ;
  54637. /**
  54638. * Creates a ribbon mesh.
  54639. * 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.
  54640. *
  54641. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54642. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54643. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54644. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54645. * 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.
  54646. * 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.
  54647. * 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
  54648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54649. * 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).
  54650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54651. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54652. * 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.
  54653. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54654. * 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
  54655. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54656. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54658. */
  54659. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54660. if (scene === void 0) { scene = null; }
  54661. var pathArray = options.pathArray;
  54662. var closeArray = options.closeArray;
  54663. var closePath = options.closePath;
  54664. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54665. var instance = options.instance;
  54666. var updatable = options.updatable;
  54667. if (instance) {
  54668. // positionFunction : ribbon case
  54669. // only pathArray and sideOrientation parameters are taken into account for positions update
  54670. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54671. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54672. var positionFunction = function (positions) {
  54673. var minlg = pathArray[0].length;
  54674. var i = 0;
  54675. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54676. for (var si = 1; si <= ns; si++) {
  54677. for (var p = 0; p < pathArray.length; p++) {
  54678. var path = pathArray[p];
  54679. var l = path.length;
  54680. minlg = (minlg < l) ? minlg : l;
  54681. var j = 0;
  54682. while (j < minlg) {
  54683. positions[i] = path[j].x;
  54684. positions[i + 1] = path[j].y;
  54685. positions[i + 2] = path[j].z;
  54686. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54687. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54688. }
  54689. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54690. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54691. }
  54692. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54693. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54694. }
  54695. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54696. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54697. }
  54698. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54699. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54700. }
  54701. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54702. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54703. }
  54704. j++;
  54705. i += 3;
  54706. }
  54707. if (instance._closePath) {
  54708. positions[i] = path[0].x;
  54709. positions[i + 1] = path[0].y;
  54710. positions[i + 2] = path[0].z;
  54711. i += 3;
  54712. }
  54713. }
  54714. }
  54715. };
  54716. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54717. positionFunction(positions);
  54718. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54719. instance._boundingInfo.update(instance._worldMatrix);
  54720. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54721. if (options.colors) {
  54722. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54723. for (var c = 0; c < options.colors.length; c++) {
  54724. colors[c * 4] = options.colors[c].r;
  54725. colors[c * 4 + 1] = options.colors[c].g;
  54726. colors[c * 4 + 2] = options.colors[c].b;
  54727. colors[c * 4 + 3] = options.colors[c].a;
  54728. }
  54729. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54730. }
  54731. if (options.uvs) {
  54732. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54733. for (var i = 0; i < options.uvs.length; i++) {
  54734. uvs[i * 2] = options.uvs[i].x;
  54735. uvs[i * 2 + 1] = options.uvs[i].y;
  54736. }
  54737. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54738. }
  54739. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54740. var indices = instance.getIndices();
  54741. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54742. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54743. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54744. if (instance._closePath) {
  54745. var indexFirst = 0;
  54746. var indexLast = 0;
  54747. for (var p = 0; p < pathArray.length; p++) {
  54748. indexFirst = instance._idx[p] * 3;
  54749. if (p + 1 < pathArray.length) {
  54750. indexLast = (instance._idx[p + 1] - 1) * 3;
  54751. }
  54752. else {
  54753. indexLast = normals.length - 3;
  54754. }
  54755. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54756. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54757. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54758. normals[indexLast] = normals[indexFirst];
  54759. normals[indexLast + 1] = normals[indexFirst + 1];
  54760. normals[indexLast + 2] = normals[indexFirst + 2];
  54761. }
  54762. }
  54763. if (!(instance.areNormalsFrozen)) {
  54764. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54765. }
  54766. }
  54767. return instance;
  54768. }
  54769. else {
  54770. var ribbon = new BABYLON.Mesh(name, scene);
  54771. ribbon._originalBuilderSideOrientation = sideOrientation;
  54772. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54773. if (closePath) {
  54774. ribbon._idx = vertexData._idx;
  54775. }
  54776. ribbon._closePath = closePath;
  54777. ribbon._closeArray = closeArray;
  54778. vertexData.applyToMesh(ribbon, updatable);
  54779. return ribbon;
  54780. }
  54781. };
  54782. /**
  54783. * Creates a cylinder or a cone mesh.
  54784. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54785. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54786. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54787. * 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.
  54788. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54789. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54790. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54791. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54792. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54793. * 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).
  54794. * 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
  54795. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54796. * 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
  54797. * 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.
  54798. * If `enclose` is false, a ring surface is one element.
  54799. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54800. * 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
  54801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54802. * 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).
  54803. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54805. */
  54806. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54807. var cylinder = new BABYLON.Mesh(name, scene);
  54808. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54809. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54810. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54811. vertexData.applyToMesh(cylinder, options.updatable);
  54812. return cylinder;
  54813. };
  54814. /**
  54815. * Creates a torus mesh.
  54816. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54817. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54818. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54819. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54821. * 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).
  54822. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54824. */
  54825. MeshBuilder.CreateTorus = function (name, options, scene) {
  54826. var torus = new BABYLON.Mesh(name, scene);
  54827. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54828. torus._originalBuilderSideOrientation = options.sideOrientation;
  54829. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54830. vertexData.applyToMesh(torus, options.updatable);
  54831. return torus;
  54832. };
  54833. /**
  54834. * Creates a torus knot mesh.
  54835. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54836. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54837. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54838. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54839. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54841. * 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).
  54842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54844. */
  54845. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54846. var torusKnot = new BABYLON.Mesh(name, scene);
  54847. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54848. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54849. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54850. vertexData.applyToMesh(torusKnot, options.updatable);
  54851. return torusKnot;
  54852. };
  54853. /**
  54854. * Creates a line system mesh.
  54855. * A line system is a pool of many lines gathered in a single mesh.
  54856. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54857. * 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.
  54858. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54859. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54860. * 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
  54861. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54862. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54863. * 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
  54864. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54866. */
  54867. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54868. var instance = options.instance;
  54869. var lines = options.lines;
  54870. var colors = options.colors;
  54871. if (instance) {
  54872. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54873. var vertexColor;
  54874. var lineColors;
  54875. if (colors) {
  54876. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54877. }
  54878. var i = 0;
  54879. var c = 0;
  54880. for (var l = 0; l < lines.length; l++) {
  54881. var points = lines[l];
  54882. for (var p = 0; p < points.length; p++) {
  54883. positions[i] = points[p].x;
  54884. positions[i + 1] = points[p].y;
  54885. positions[i + 2] = points[p].z;
  54886. if (colors && vertexColor) {
  54887. lineColors = colors[l];
  54888. vertexColor[c] = lineColors[p].r;
  54889. vertexColor[c + 1] = lineColors[p].g;
  54890. vertexColor[c + 2] = lineColors[p].b;
  54891. vertexColor[c + 3] = lineColors[p].a;
  54892. c += 4;
  54893. }
  54894. i += 3;
  54895. }
  54896. }
  54897. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54898. if (colors && vertexColor) {
  54899. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54900. }
  54901. return instance;
  54902. }
  54903. // line system creation
  54904. var useVertexColor = (colors) ? true : false;
  54905. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54906. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54907. vertexData.applyToMesh(lineSystem, options.updatable);
  54908. return lineSystem;
  54909. };
  54910. /**
  54911. * Creates a line mesh.
  54912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54913. * 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.
  54914. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54915. * The parameter `points` is an array successive Vector3.
  54916. * 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
  54917. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54918. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54919. * When updating an instance, remember that only point positions can change, not the number of points.
  54920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54921. */
  54922. MeshBuilder.CreateLines = function (name, options, scene) {
  54923. if (scene === void 0) { scene = null; }
  54924. var colors = (options.colors) ? [options.colors] : null;
  54925. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54926. return lines;
  54927. };
  54928. /**
  54929. * Creates a dashed line mesh.
  54930. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54931. * 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.
  54932. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54933. * The parameter `points` is an array successive Vector3.
  54934. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54935. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54936. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54937. * 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
  54938. * When updating an instance, remember that only point positions can change, not the number of points.
  54939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54940. */
  54941. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54942. if (scene === void 0) { scene = null; }
  54943. var points = options.points;
  54944. var instance = options.instance;
  54945. var gapSize = options.gapSize || 1;
  54946. var dashSize = options.dashSize || 3;
  54947. if (instance) {
  54948. var positionFunction = function (positions) {
  54949. var curvect = BABYLON.Vector3.Zero();
  54950. var nbSeg = positions.length / 6;
  54951. var lg = 0;
  54952. var nb = 0;
  54953. var shft = 0;
  54954. var dashshft = 0;
  54955. var curshft = 0;
  54956. var p = 0;
  54957. var i = 0;
  54958. var j = 0;
  54959. for (i = 0; i < points.length - 1; i++) {
  54960. points[i + 1].subtractToRef(points[i], curvect);
  54961. lg += curvect.length();
  54962. }
  54963. shft = lg / nbSeg;
  54964. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54965. for (i = 0; i < points.length - 1; i++) {
  54966. points[i + 1].subtractToRef(points[i], curvect);
  54967. nb = Math.floor(curvect.length() / shft);
  54968. curvect.normalize();
  54969. j = 0;
  54970. while (j < nb && p < positions.length) {
  54971. curshft = shft * j;
  54972. positions[p] = points[i].x + curshft * curvect.x;
  54973. positions[p + 1] = points[i].y + curshft * curvect.y;
  54974. positions[p + 2] = points[i].z + curshft * curvect.z;
  54975. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54976. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54977. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54978. p += 6;
  54979. j++;
  54980. }
  54981. }
  54982. while (p < positions.length) {
  54983. positions[p] = points[i].x;
  54984. positions[p + 1] = points[i].y;
  54985. positions[p + 2] = points[i].z;
  54986. p += 3;
  54987. }
  54988. };
  54989. instance.updateMeshPositions(positionFunction, false);
  54990. return instance;
  54991. }
  54992. // dashed lines creation
  54993. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54994. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54995. vertexData.applyToMesh(dashedLines, options.updatable);
  54996. dashedLines.dashSize = dashSize;
  54997. dashedLines.gapSize = gapSize;
  54998. return dashedLines;
  54999. };
  55000. /**
  55001. * Creates an extruded shape mesh.
  55002. * 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.
  55003. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55004. *
  55005. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55006. * 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
  55007. * extruded along the Z axis.
  55008. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55009. * 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.
  55010. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55011. * 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
  55012. * 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
  55013. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55015. * 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).
  55016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55017. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55019. */
  55020. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55021. if (scene === void 0) { scene = null; }
  55022. var path = options.path;
  55023. var shape = options.shape;
  55024. var scale = options.scale || 1;
  55025. var rotation = options.rotation || 0;
  55026. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55027. var updatable = options.updatable;
  55028. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55029. var instance = options.instance || null;
  55030. var invertUV = options.invertUV || false;
  55031. 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);
  55032. };
  55033. /**
  55034. * Creates an custom extruded shape mesh.
  55035. * 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.
  55036. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55037. *
  55038. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55039. * 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
  55040. * extruded along the Z axis.
  55041. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55042. * 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
  55043. * and the distance of this point from the begining of the path :
  55044. * ```javascript
  55045. * var rotationFunction = function(i, distance) {
  55046. * // do things
  55047. * return rotationValue; }
  55048. * ```
  55049. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55050. * 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
  55051. * and the distance of this point from the begining of the path :
  55052. * ```javascript
  55053. * var scaleFunction = function(i, distance) {
  55054. * // do things
  55055. * return scaleValue;}
  55056. * ```
  55057. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55058. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55059. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55060. * 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
  55061. * 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
  55062. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55064. * 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).
  55065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55066. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55068. */
  55069. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55070. var path = options.path;
  55071. var shape = options.shape;
  55072. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55073. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55074. var ribbonCloseArray = options.ribbonCloseArray || false;
  55075. var ribbonClosePath = options.ribbonClosePath || false;
  55076. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55077. var updatable = options.updatable;
  55078. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55079. var instance = options.instance;
  55080. var invertUV = options.invertUV || false;
  55081. 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);
  55082. };
  55083. /**
  55084. * Creates lathe mesh.
  55085. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55087. *
  55088. * 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
  55089. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55090. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55091. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55092. * 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.
  55093. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55094. * 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
  55095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55096. * 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).
  55097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55098. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55100. */
  55101. MeshBuilder.CreateLathe = function (name, options, scene) {
  55102. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55103. var closed = (options.closed === undefined) ? true : options.closed;
  55104. var shape = options.shape;
  55105. var radius = options.radius || 1;
  55106. var tessellation = options.tessellation || 64;
  55107. var updatable = options.updatable;
  55108. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55109. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55110. var pi2 = Math.PI * 2;
  55111. var paths = new Array();
  55112. var invertUV = options.invertUV || false;
  55113. var i = 0;
  55114. var p = 0;
  55115. var step = pi2 / tessellation * arc;
  55116. var rotated;
  55117. var path = new Array();
  55118. ;
  55119. for (i = 0; i <= tessellation; i++) {
  55120. var path = [];
  55121. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55122. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55123. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55124. }
  55125. for (p = 0; p < shape.length; p++) {
  55126. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55127. path.push(rotated);
  55128. }
  55129. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55130. 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));
  55131. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55132. }
  55133. paths.push(path);
  55134. }
  55135. // lathe ribbon
  55136. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55137. return lathe;
  55138. };
  55139. /**
  55140. * Creates a plane mesh.
  55141. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55142. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55143. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55144. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55146. * 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).
  55147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55149. */
  55150. MeshBuilder.CreatePlane = function (name, options, scene) {
  55151. var plane = new BABYLON.Mesh(name, scene);
  55152. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55153. plane._originalBuilderSideOrientation = options.sideOrientation;
  55154. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55155. vertexData.applyToMesh(plane, options.updatable);
  55156. if (options.sourcePlane) {
  55157. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55158. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55159. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55160. plane.rotate(vectorProduct, product);
  55161. }
  55162. return plane;
  55163. };
  55164. /**
  55165. * Creates a ground mesh.
  55166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55167. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55168. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55170. */
  55171. MeshBuilder.CreateGround = function (name, options, scene) {
  55172. var ground = new BABYLON.GroundMesh(name, scene);
  55173. ground._setReady(false);
  55174. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55175. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55176. ground._width = options.width || 1;
  55177. ground._height = options.height || 1;
  55178. ground._maxX = ground._width / 2;
  55179. ground._maxZ = ground._height / 2;
  55180. ground._minX = -ground._maxX;
  55181. ground._minZ = -ground._maxZ;
  55182. var vertexData = BABYLON.VertexData.CreateGround(options);
  55183. vertexData.applyToMesh(ground, options.updatable);
  55184. ground._setReady(true);
  55185. return ground;
  55186. };
  55187. /**
  55188. * Creates a tiled ground mesh.
  55189. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55190. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55191. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55192. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55193. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55194. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55195. * numbers of subdivisions on the ground width and height of each tile.
  55196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55197. */
  55198. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55199. var tiledGround = new BABYLON.Mesh(name, scene);
  55200. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55201. vertexData.applyToMesh(tiledGround, options.updatable);
  55202. return tiledGround;
  55203. };
  55204. /**
  55205. * Creates a ground mesh from a height map.
  55206. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55207. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55208. * The parameter `url` sets the URL of the height map image resource.
  55209. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55210. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55211. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55212. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55213. * 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.
  55214. * 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).
  55215. * This function is passed the newly built mesh :
  55216. * ```javascript
  55217. * function(mesh) { // do things
  55218. * return; }
  55219. * ```
  55220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55221. */
  55222. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55223. var width = options.width || 10.0;
  55224. var height = options.height || 10.0;
  55225. var subdivisions = options.subdivisions || 1 | 0;
  55226. var minHeight = options.minHeight || 0.0;
  55227. var maxHeight = options.maxHeight || 1.0;
  55228. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55229. var updatable = options.updatable;
  55230. var onReady = options.onReady;
  55231. var ground = new BABYLON.GroundMesh(name, scene);
  55232. ground._subdivisionsX = subdivisions;
  55233. ground._subdivisionsY = subdivisions;
  55234. ground._width = width;
  55235. ground._height = height;
  55236. ground._maxX = ground._width / 2.0;
  55237. ground._maxZ = ground._height / 2.0;
  55238. ground._minX = -ground._maxX;
  55239. ground._minZ = -ground._maxZ;
  55240. ground._setReady(false);
  55241. var onload = function (img) {
  55242. // Getting height map data
  55243. var canvas = document.createElement("canvas");
  55244. var context = canvas.getContext("2d");
  55245. if (!context) {
  55246. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55247. }
  55248. if (scene.isDisposed) {
  55249. return;
  55250. }
  55251. var bufferWidth = img.width;
  55252. var bufferHeight = img.height;
  55253. canvas.width = bufferWidth;
  55254. canvas.height = bufferHeight;
  55255. context.drawImage(img, 0, 0);
  55256. // Create VertexData from map data
  55257. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55258. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55259. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55260. width: width, height: height,
  55261. subdivisions: subdivisions,
  55262. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55263. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55264. });
  55265. vertexData.applyToMesh(ground, updatable);
  55266. ground._setReady(true);
  55267. //execute ready callback, if set
  55268. if (onReady) {
  55269. onReady(ground);
  55270. }
  55271. };
  55272. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55273. return ground;
  55274. };
  55275. /**
  55276. * Creates a polygon mesh.
  55277. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55278. * 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.
  55279. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55281. * 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).
  55282. * Remember you can only change the shape positions, not their number when updating a polygon.
  55283. */
  55284. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55285. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55286. var shape = options.shape;
  55287. var holes = options.holes || [];
  55288. var depth = options.depth || 0;
  55289. var contours = [];
  55290. var hole = [];
  55291. for (var i = 0; i < shape.length; i++) {
  55292. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55293. }
  55294. var epsilon = 0.00000001;
  55295. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55296. contours.pop();
  55297. }
  55298. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55299. for (var hNb = 0; hNb < holes.length; hNb++) {
  55300. hole = [];
  55301. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55302. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55303. }
  55304. polygonTriangulation.addHole(hole);
  55305. }
  55306. var polygon = polygonTriangulation.build(options.updatable, depth);
  55307. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55308. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55309. vertexData.applyToMesh(polygon, options.updatable);
  55310. return polygon;
  55311. };
  55312. ;
  55313. /**
  55314. * Creates an extruded polygon mesh, with depth in the Y direction.
  55315. * 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).
  55316. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55317. */
  55318. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55319. return MeshBuilder.CreatePolygon(name, options, scene);
  55320. };
  55321. ;
  55322. /**
  55323. * Creates a tube mesh.
  55324. * 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.
  55325. *
  55326. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55327. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55328. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55329. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55330. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55331. * 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.
  55332. * It must return a radius value (positive float) :
  55333. * ```javascript
  55334. * var radiusFunction = function(i, distance) {
  55335. * // do things
  55336. * return radius; }
  55337. * ```
  55338. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55339. * 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
  55340. * 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
  55341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55342. * 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).
  55343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55344. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55346. */
  55347. MeshBuilder.CreateTube = function (name, options, scene) {
  55348. var path = options.path;
  55349. var instance = options.instance;
  55350. var radius = 1.0;
  55351. if (instance) {
  55352. radius = instance.radius;
  55353. }
  55354. if (options.radius !== undefined) {
  55355. radius = options.radius;
  55356. }
  55357. ;
  55358. var tessellation = options.tessellation || 64 | 0;
  55359. var radiusFunction = options.radiusFunction || null;
  55360. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55361. var invertUV = options.invertUV || false;
  55362. var updatable = options.updatable;
  55363. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55364. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55365. // tube geometry
  55366. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55367. var tangents = path3D.getTangents();
  55368. var normals = path3D.getNormals();
  55369. var distances = path3D.getDistances();
  55370. var pi2 = Math.PI * 2;
  55371. var step = pi2 / tessellation * arc;
  55372. var returnRadius = function () { return radius; };
  55373. var radiusFunctionFinal = radiusFunction || returnRadius;
  55374. var circlePath;
  55375. var rad;
  55376. var normal;
  55377. var rotated;
  55378. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55379. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55380. for (var i = 0; i < path.length; i++) {
  55381. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55382. circlePath = Array(); // current circle array
  55383. normal = normals[i]; // current normal
  55384. for (var t = 0; t < tessellation; t++) {
  55385. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55386. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55387. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55388. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55389. circlePath[t] = rotated;
  55390. }
  55391. circlePaths[index] = circlePath;
  55392. index++;
  55393. }
  55394. // cap
  55395. var capPath = function (nbPoints, pathIndex) {
  55396. var pointCap = Array();
  55397. for (var i = 0; i < nbPoints; i++) {
  55398. pointCap.push(path[pathIndex]);
  55399. }
  55400. return pointCap;
  55401. };
  55402. switch (cap) {
  55403. case BABYLON.Mesh.NO_CAP:
  55404. break;
  55405. case BABYLON.Mesh.CAP_START:
  55406. circlePaths[0] = capPath(tessellation, 0);
  55407. circlePaths[1] = circlePaths[2].slice(0);
  55408. break;
  55409. case BABYLON.Mesh.CAP_END:
  55410. circlePaths[index] = circlePaths[index - 1].slice(0);
  55411. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55412. break;
  55413. case BABYLON.Mesh.CAP_ALL:
  55414. circlePaths[0] = capPath(tessellation, 0);
  55415. circlePaths[1] = circlePaths[2].slice(0);
  55416. circlePaths[index] = circlePaths[index - 1].slice(0);
  55417. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55418. break;
  55419. default:
  55420. break;
  55421. }
  55422. return circlePaths;
  55423. };
  55424. var path3D;
  55425. var pathArray;
  55426. if (instance) {
  55427. var arc = options.arc || instance.arc;
  55428. path3D = (instance.path3D).update(path);
  55429. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55430. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55431. instance.path3D = path3D;
  55432. instance.pathArray = pathArray;
  55433. instance.arc = arc;
  55434. instance.radius = radius;
  55435. return instance;
  55436. }
  55437. // tube creation
  55438. path3D = new BABYLON.Path3D(path);
  55439. var newPathArray = new Array();
  55440. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55441. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55442. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55443. tube.pathArray = pathArray;
  55444. tube.path3D = path3D;
  55445. tube.tessellation = tessellation;
  55446. tube.cap = cap;
  55447. tube.arc = options.arc;
  55448. tube.radius = radius;
  55449. return tube;
  55450. };
  55451. /**
  55452. * Creates a polyhedron mesh.
  55453. *
  55454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55455. * 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
  55456. * to choose the wanted type.
  55457. * The parameter `size` (positive float, default 1) sets the polygon size.
  55458. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55459. * 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`.
  55460. * 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
  55461. * 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)`).
  55462. * 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
  55463. * 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.
  55464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55465. * 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).
  55466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55468. */
  55469. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55470. var polyhedron = new BABYLON.Mesh(name, scene);
  55471. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55472. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55473. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55474. vertexData.applyToMesh(polyhedron, options.updatable);
  55475. return polyhedron;
  55476. };
  55477. /**
  55478. * Creates a decal mesh.
  55479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55480. * 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.
  55481. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55482. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55483. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55484. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55485. */
  55486. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55487. var indices = sourceMesh.getIndices();
  55488. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55489. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55490. var position = options.position || BABYLON.Vector3.Zero();
  55491. var normal = options.normal || BABYLON.Vector3.Up();
  55492. var size = options.size || BABYLON.Vector3.One();
  55493. var angle = options.angle || 0;
  55494. // Getting correct rotation
  55495. if (!normal) {
  55496. var target = new BABYLON.Vector3(0, 0, 1);
  55497. var camera = sourceMesh.getScene().activeCamera;
  55498. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55499. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55500. }
  55501. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55502. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55503. var pitch = Math.atan2(normal.y, len);
  55504. // Matrix
  55505. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55506. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55507. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55508. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55509. var vertexData = new BABYLON.VertexData();
  55510. vertexData.indices = [];
  55511. vertexData.positions = [];
  55512. vertexData.normals = [];
  55513. vertexData.uvs = [];
  55514. var currentVertexDataIndex = 0;
  55515. var extractDecalVector3 = function (indexId) {
  55516. var result = new BABYLON.PositionNormalVertex();
  55517. if (!indices || !positions || !normals) {
  55518. return result;
  55519. }
  55520. var vertexId = indices[indexId];
  55521. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55522. // Send vector to decal local world
  55523. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55524. // Get normal
  55525. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55526. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55527. return result;
  55528. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55529. var clip = function (vertices, axis) {
  55530. if (vertices.length === 0) {
  55531. return vertices;
  55532. }
  55533. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55534. var clipVertices = function (v0, v1) {
  55535. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55536. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55537. };
  55538. var result = new Array();
  55539. for (var index = 0; index < vertices.length; index += 3) {
  55540. var v1Out;
  55541. var v2Out;
  55542. var v3Out;
  55543. var total = 0;
  55544. var nV1 = null;
  55545. var nV2 = null;
  55546. var nV3 = null;
  55547. var nV4 = null;
  55548. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55549. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55550. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55551. v1Out = d1 > 0;
  55552. v2Out = d2 > 0;
  55553. v3Out = d3 > 0;
  55554. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55555. switch (total) {
  55556. case 0:
  55557. result.push(vertices[index]);
  55558. result.push(vertices[index + 1]);
  55559. result.push(vertices[index + 2]);
  55560. break;
  55561. case 1:
  55562. if (v1Out) {
  55563. nV1 = vertices[index + 1];
  55564. nV2 = vertices[index + 2];
  55565. nV3 = clipVertices(vertices[index], nV1);
  55566. nV4 = clipVertices(vertices[index], nV2);
  55567. }
  55568. if (v2Out) {
  55569. nV1 = vertices[index];
  55570. nV2 = vertices[index + 2];
  55571. nV3 = clipVertices(vertices[index + 1], nV1);
  55572. nV4 = clipVertices(vertices[index + 1], nV2);
  55573. result.push(nV3);
  55574. result.push(nV2.clone());
  55575. result.push(nV1.clone());
  55576. result.push(nV2.clone());
  55577. result.push(nV3.clone());
  55578. result.push(nV4);
  55579. break;
  55580. }
  55581. if (v3Out) {
  55582. nV1 = vertices[index];
  55583. nV2 = vertices[index + 1];
  55584. nV3 = clipVertices(vertices[index + 2], nV1);
  55585. nV4 = clipVertices(vertices[index + 2], nV2);
  55586. }
  55587. if (nV1 && nV2 && nV3 && nV4) {
  55588. result.push(nV1.clone());
  55589. result.push(nV2.clone());
  55590. result.push(nV3);
  55591. result.push(nV4);
  55592. result.push(nV3.clone());
  55593. result.push(nV2.clone());
  55594. }
  55595. break;
  55596. case 2:
  55597. if (!v1Out) {
  55598. nV1 = vertices[index].clone();
  55599. nV2 = clipVertices(nV1, vertices[index + 1]);
  55600. nV3 = clipVertices(nV1, vertices[index + 2]);
  55601. result.push(nV1);
  55602. result.push(nV2);
  55603. result.push(nV3);
  55604. }
  55605. if (!v2Out) {
  55606. nV1 = vertices[index + 1].clone();
  55607. nV2 = clipVertices(nV1, vertices[index + 2]);
  55608. nV3 = clipVertices(nV1, vertices[index]);
  55609. result.push(nV1);
  55610. result.push(nV2);
  55611. result.push(nV3);
  55612. }
  55613. if (!v3Out) {
  55614. nV1 = vertices[index + 2].clone();
  55615. nV2 = clipVertices(nV1, vertices[index]);
  55616. nV3 = clipVertices(nV1, vertices[index + 1]);
  55617. result.push(nV1);
  55618. result.push(nV2);
  55619. result.push(nV3);
  55620. }
  55621. break;
  55622. case 3:
  55623. break;
  55624. }
  55625. }
  55626. return result;
  55627. };
  55628. for (var index = 0; index < indices.length; index += 3) {
  55629. var faceVertices = new Array();
  55630. faceVertices.push(extractDecalVector3(index));
  55631. faceVertices.push(extractDecalVector3(index + 1));
  55632. faceVertices.push(extractDecalVector3(index + 2));
  55633. // Clip
  55634. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55635. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55636. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55637. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55638. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55639. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55640. if (faceVertices.length === 0) {
  55641. continue;
  55642. }
  55643. // Add UVs and get back to world
  55644. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55645. var vertex = faceVertices[vIndex];
  55646. //TODO check for Int32Array | Uint32Array | Uint16Array
  55647. vertexData.indices.push(currentVertexDataIndex);
  55648. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55649. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55650. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55651. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55652. currentVertexDataIndex++;
  55653. }
  55654. }
  55655. // Return mesh
  55656. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55657. vertexData.applyToMesh(decal);
  55658. decal.position = position.clone();
  55659. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55660. return decal;
  55661. };
  55662. // Privates
  55663. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55664. // extrusion geometry
  55665. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55666. var tangents = path3D.getTangents();
  55667. var normals = path3D.getNormals();
  55668. var binormals = path3D.getBinormals();
  55669. var distances = path3D.getDistances();
  55670. var angle = 0;
  55671. var returnScale = function () { return scale !== null ? scale : 1; };
  55672. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55673. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55674. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55675. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55676. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55677. for (var i = 0; i < curve.length; i++) {
  55678. var shapePath = new Array();
  55679. var angleStep = rotate(i, distances[i]);
  55680. var scaleRatio = scl(i, distances[i]);
  55681. for (var p = 0; p < shape.length; p++) {
  55682. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55683. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55684. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55685. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55686. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55687. shapePath[p] = rotated;
  55688. }
  55689. shapePaths[index] = shapePath;
  55690. angle += angleStep;
  55691. index++;
  55692. }
  55693. // cap
  55694. var capPath = function (shapePath) {
  55695. var pointCap = Array();
  55696. var barycenter = BABYLON.Vector3.Zero();
  55697. var i;
  55698. for (i = 0; i < shapePath.length; i++) {
  55699. barycenter.addInPlace(shapePath[i]);
  55700. }
  55701. barycenter.scaleInPlace(1.0 / shapePath.length);
  55702. for (i = 0; i < shapePath.length; i++) {
  55703. pointCap.push(barycenter);
  55704. }
  55705. return pointCap;
  55706. };
  55707. switch (cap) {
  55708. case BABYLON.Mesh.NO_CAP:
  55709. break;
  55710. case BABYLON.Mesh.CAP_START:
  55711. shapePaths[0] = capPath(shapePaths[2]);
  55712. shapePaths[1] = shapePaths[2];
  55713. break;
  55714. case BABYLON.Mesh.CAP_END:
  55715. shapePaths[index] = shapePaths[index - 1];
  55716. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55717. break;
  55718. case BABYLON.Mesh.CAP_ALL:
  55719. shapePaths[0] = capPath(shapePaths[2]);
  55720. shapePaths[1] = shapePaths[2];
  55721. shapePaths[index] = shapePaths[index - 1];
  55722. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55723. break;
  55724. default:
  55725. break;
  55726. }
  55727. return shapePaths;
  55728. };
  55729. var path3D;
  55730. var pathArray;
  55731. if (instance) {
  55732. path3D = (instance.path3D).update(curve);
  55733. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55734. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55735. return instance;
  55736. }
  55737. // extruded shape creation
  55738. path3D = new BABYLON.Path3D(curve);
  55739. var newShapePaths = new Array();
  55740. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55741. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55742. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55743. extrudedGeneric.pathArray = pathArray;
  55744. extrudedGeneric.path3D = path3D;
  55745. extrudedGeneric.cap = cap;
  55746. return extrudedGeneric;
  55747. };
  55748. return MeshBuilder;
  55749. }());
  55750. BABYLON.MeshBuilder = MeshBuilder;
  55751. })(BABYLON || (BABYLON = {}));
  55752. //# sourceMappingURL=babylon.meshBuilder.js.map
  55753. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  55754. var BABYLON;
  55755. (function (BABYLON) {
  55756. /**
  55757. * Draco compression (https://google.github.io/draco/)
  55758. */
  55759. var DracoCompression = /** @class */ (function () {
  55760. /**
  55761. * Constructor
  55762. * @param numWorkers The number of workers for async operations
  55763. */
  55764. function DracoCompression(numWorkers) {
  55765. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55766. var workers = new Array(numWorkers);
  55767. for (var i = 0; i < workers.length; i++) {
  55768. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  55769. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55770. workers[i] = worker;
  55771. }
  55772. this._workerPool = new BABYLON.WorkerPool(workers);
  55773. }
  55774. /**
  55775. * Stop all async operations and release resources.
  55776. */
  55777. DracoCompression.prototype.dispose = function () {
  55778. this._workerPool.dispose();
  55779. delete this._workerPool;
  55780. };
  55781. /**
  55782. * Decode Draco compressed mesh data to vertex data.
  55783. * @param data The array buffer view for the Draco compression data
  55784. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55785. * @returns A promise that resolves with the decoded vertex data
  55786. */
  55787. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55788. var _this = this;
  55789. return new Promise(function (resolve, reject) {
  55790. _this._workerPool.push(function (worker, onComplete) {
  55791. var vertexData = new BABYLON.VertexData();
  55792. var onError = function (error) {
  55793. worker.removeEventListener("error", onError);
  55794. worker.removeEventListener("message", onMessage);
  55795. reject(error);
  55796. onComplete();
  55797. };
  55798. var onMessage = function (message) {
  55799. if (message.data === "done") {
  55800. worker.removeEventListener("error", onError);
  55801. worker.removeEventListener("message", onMessage);
  55802. resolve(vertexData);
  55803. onComplete();
  55804. }
  55805. else if (message.data.id === "indices") {
  55806. vertexData.indices = message.data.value;
  55807. }
  55808. else {
  55809. vertexData.set(message.data.value, message.data.id);
  55810. }
  55811. };
  55812. worker.addEventListener("error", onError);
  55813. worker.addEventListener("message", onMessage);
  55814. var dataCopy = new Uint8Array(data.byteLength);
  55815. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55816. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55817. });
  55818. });
  55819. };
  55820. /**
  55821. * The worker function that gets converted to a blob url to pass into a worker.
  55822. */
  55823. DracoCompression._Worker = function () {
  55824. // self is actually a DedicatedWorkerGlobalScope
  55825. var _self = self;
  55826. var decodeMesh = function (data, attributes) {
  55827. var dracoModule = new DracoDecoderModule();
  55828. var buffer = new dracoModule.DecoderBuffer();
  55829. buffer.Init(data, data.byteLength);
  55830. var decoder = new dracoModule.Decoder();
  55831. var geometry;
  55832. var status;
  55833. try {
  55834. var type = decoder.GetEncodedGeometryType(buffer);
  55835. switch (type) {
  55836. case dracoModule.TRIANGULAR_MESH:
  55837. geometry = new dracoModule.Mesh();
  55838. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55839. break;
  55840. case dracoModule.POINT_CLOUD:
  55841. geometry = new dracoModule.PointCloud();
  55842. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55843. break;
  55844. default:
  55845. throw new Error("Invalid geometry type " + type);
  55846. }
  55847. if (!status.ok() || !geometry.ptr) {
  55848. throw new Error(status.error_msg());
  55849. }
  55850. var numPoints = geometry.num_points();
  55851. if (type === dracoModule.TRIANGULAR_MESH) {
  55852. var numFaces = geometry.num_faces();
  55853. var faceIndices = new dracoModule.DracoInt32Array();
  55854. try {
  55855. var indices = new Uint32Array(numFaces * 3);
  55856. for (var i = 0; i < numFaces; i++) {
  55857. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55858. var offset = i * 3;
  55859. indices[offset + 0] = faceIndices.GetValue(0);
  55860. indices[offset + 1] = faceIndices.GetValue(1);
  55861. indices[offset + 2] = faceIndices.GetValue(2);
  55862. }
  55863. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55864. }
  55865. finally {
  55866. dracoModule.destroy(faceIndices);
  55867. }
  55868. }
  55869. for (var kind in attributes) {
  55870. var uniqueId = attributes[kind];
  55871. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55872. var dracoData = new dracoModule.DracoFloat32Array();
  55873. try {
  55874. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55875. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55876. for (var i = 0; i < babylonData.length; i++) {
  55877. babylonData[i] = dracoData.GetValue(i);
  55878. }
  55879. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55880. }
  55881. finally {
  55882. dracoModule.destroy(dracoData);
  55883. }
  55884. }
  55885. }
  55886. finally {
  55887. if (geometry) {
  55888. dracoModule.destroy(geometry);
  55889. }
  55890. dracoModule.destroy(decoder);
  55891. dracoModule.destroy(buffer);
  55892. }
  55893. _self.postMessage("done");
  55894. };
  55895. _self.onmessage = function (event) {
  55896. switch (event.data.id) {
  55897. case "initDecoder": {
  55898. importScripts(event.data.url);
  55899. break;
  55900. }
  55901. case "decodeMesh": {
  55902. decodeMesh(event.data.data, event.data.attributes);
  55903. break;
  55904. }
  55905. }
  55906. };
  55907. };
  55908. DracoCompression._GetDefaultDecoderUrl = function () {
  55909. for (var i = 0; i < document.scripts.length; i++) {
  55910. if (document.scripts[i].type === "text/x-draco-decoder") {
  55911. return document.scripts[i].src;
  55912. }
  55913. }
  55914. return null;
  55915. };
  55916. /**
  55917. * Gets the url to the draco decoder if available.
  55918. */
  55919. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  55920. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55921. return DracoCompression;
  55922. }());
  55923. BABYLON.DracoCompression = DracoCompression;
  55924. })(BABYLON || (BABYLON = {}));
  55925. //# sourceMappingURL=babylon.dracoCompression.js.map
  55926. var BABYLON;
  55927. (function (BABYLON) {
  55928. var AudioEngine = /** @class */ (function () {
  55929. function AudioEngine() {
  55930. this._audioContext = null;
  55931. this._audioContextInitialized = false;
  55932. this.canUseWebAudio = false;
  55933. this.WarnedWebAudioUnsupported = false;
  55934. this.unlocked = false;
  55935. this.isMP3supported = false;
  55936. this.isOGGsupported = false;
  55937. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55938. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55939. this.canUseWebAudio = true;
  55940. }
  55941. var audioElem = document.createElement('audio');
  55942. try {
  55943. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55944. this.isMP3supported = true;
  55945. }
  55946. }
  55947. catch (e) {
  55948. // protect error during capability check.
  55949. }
  55950. try {
  55951. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55952. this.isOGGsupported = true;
  55953. }
  55954. }
  55955. catch (e) {
  55956. // protect error during capability check.
  55957. }
  55958. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55959. this._unlockiOSaudio();
  55960. }
  55961. else {
  55962. this.unlocked = true;
  55963. }
  55964. }
  55965. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55966. get: function () {
  55967. if (!this._audioContextInitialized) {
  55968. this._initializeAudioContext();
  55969. }
  55970. return this._audioContext;
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. AudioEngine.prototype._unlockiOSaudio = function () {
  55976. var _this = this;
  55977. var unlockaudio = function () {
  55978. if (!_this.audioContext) {
  55979. return;
  55980. }
  55981. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55982. var source = _this.audioContext.createBufferSource();
  55983. source.buffer = buffer;
  55984. source.connect(_this.audioContext.destination);
  55985. source.start(0);
  55986. setTimeout(function () {
  55987. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55988. _this.unlocked = true;
  55989. window.removeEventListener('touchend', unlockaudio, false);
  55990. if (_this.onAudioUnlocked) {
  55991. _this.onAudioUnlocked();
  55992. }
  55993. }
  55994. }, 0);
  55995. };
  55996. window.addEventListener('touchend', unlockaudio, false);
  55997. };
  55998. AudioEngine.prototype._initializeAudioContext = function () {
  55999. try {
  56000. if (this.canUseWebAudio) {
  56001. this._audioContext = new AudioContext();
  56002. // create a global volume gain node
  56003. this.masterGain = this._audioContext.createGain();
  56004. this.masterGain.gain.value = 1;
  56005. this.masterGain.connect(this._audioContext.destination);
  56006. this._audioContextInitialized = true;
  56007. }
  56008. }
  56009. catch (e) {
  56010. this.canUseWebAudio = false;
  56011. BABYLON.Tools.Error("Web Audio: " + e.message);
  56012. }
  56013. };
  56014. AudioEngine.prototype.dispose = function () {
  56015. if (this.canUseWebAudio && this._audioContextInitialized) {
  56016. if (this._connectedAnalyser && this._audioContext) {
  56017. this._connectedAnalyser.stopDebugCanvas();
  56018. this._connectedAnalyser.dispose();
  56019. this.masterGain.disconnect();
  56020. this.masterGain.connect(this._audioContext.destination);
  56021. this._connectedAnalyser = null;
  56022. }
  56023. this.masterGain.gain.value = 1;
  56024. }
  56025. this.WarnedWebAudioUnsupported = false;
  56026. };
  56027. AudioEngine.prototype.getGlobalVolume = function () {
  56028. if (this.canUseWebAudio && this._audioContextInitialized) {
  56029. return this.masterGain.gain.value;
  56030. }
  56031. else {
  56032. return -1;
  56033. }
  56034. };
  56035. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56036. if (this.canUseWebAudio && this._audioContextInitialized) {
  56037. this.masterGain.gain.value = newVolume;
  56038. }
  56039. };
  56040. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56041. if (this._connectedAnalyser) {
  56042. this._connectedAnalyser.stopDebugCanvas();
  56043. }
  56044. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56045. this._connectedAnalyser = analyser;
  56046. this.masterGain.disconnect();
  56047. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56048. }
  56049. };
  56050. return AudioEngine;
  56051. }());
  56052. BABYLON.AudioEngine = AudioEngine;
  56053. })(BABYLON || (BABYLON = {}));
  56054. //# sourceMappingURL=babylon.audioEngine.js.map
  56055. var BABYLON;
  56056. (function (BABYLON) {
  56057. var Sound = /** @class */ (function () {
  56058. /**
  56059. * Create a sound and attach it to a scene
  56060. * @param name Name of your sound
  56061. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56062. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56063. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56064. */
  56065. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56066. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56067. var _this = this;
  56068. this.autoplay = false;
  56069. this.loop = false;
  56070. this.useCustomAttenuation = false;
  56071. this.spatialSound = false;
  56072. this.refDistance = 1;
  56073. this.rolloffFactor = 1;
  56074. this.maxDistance = 100;
  56075. this.distanceModel = "linear";
  56076. this._panningModel = "equalpower";
  56077. this._playbackRate = 1;
  56078. this._streaming = false;
  56079. this._startTime = 0;
  56080. this._startOffset = 0;
  56081. this._position = BABYLON.Vector3.Zero();
  56082. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56083. this._volume = 1;
  56084. this._isReadyToPlay = false;
  56085. this.isPlaying = false;
  56086. this.isPaused = false;
  56087. this._isDirectional = false;
  56088. // Used if you'd like to create a directional sound.
  56089. // If not set, the sound will be omnidirectional
  56090. this._coneInnerAngle = 360;
  56091. this._coneOuterAngle = 360;
  56092. this._coneOuterGain = 0;
  56093. this._isOutputConnected = false;
  56094. this._urlType = "Unknown";
  56095. this.name = name;
  56096. this._scene = scene;
  56097. this._readyToPlayCallback = readyToPlayCallback;
  56098. // Default custom attenuation function is a linear attenuation
  56099. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56100. if (currentDistance < maxDistance) {
  56101. return currentVolume * (1 - currentDistance / maxDistance);
  56102. }
  56103. else {
  56104. return 0;
  56105. }
  56106. };
  56107. if (options) {
  56108. this.autoplay = options.autoplay || false;
  56109. this.loop = options.loop || false;
  56110. // if volume === 0, we need another way to check this option
  56111. if (options.volume !== undefined) {
  56112. this._volume = options.volume;
  56113. }
  56114. this.spatialSound = options.spatialSound || false;
  56115. this.maxDistance = options.maxDistance || 100;
  56116. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56117. this.rolloffFactor = options.rolloffFactor || 1;
  56118. this.refDistance = options.refDistance || 1;
  56119. this.distanceModel = options.distanceModel || "linear";
  56120. this._playbackRate = options.playbackRate || 1;
  56121. this._streaming = options.streaming || false;
  56122. }
  56123. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56124. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56125. this._soundGain.gain.value = this._volume;
  56126. this._inputAudioNode = this._soundGain;
  56127. this._ouputAudioNode = this._soundGain;
  56128. if (this.spatialSound) {
  56129. this._createSpatialParameters();
  56130. }
  56131. this._scene.mainSoundTrack.AddSound(this);
  56132. var validParameter = true;
  56133. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56134. if (urlOrArrayBuffer) {
  56135. if (typeof (urlOrArrayBuffer) === "string")
  56136. this._urlType = "String";
  56137. if (Array.isArray(urlOrArrayBuffer))
  56138. this._urlType = "Array";
  56139. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56140. this._urlType = "ArrayBuffer";
  56141. var urls = [];
  56142. var codecSupportedFound = false;
  56143. switch (this._urlType) {
  56144. case "ArrayBuffer":
  56145. if (urlOrArrayBuffer.byteLength > 0) {
  56146. codecSupportedFound = true;
  56147. this._soundLoaded(urlOrArrayBuffer);
  56148. }
  56149. break;
  56150. case "String":
  56151. urls.push(urlOrArrayBuffer);
  56152. case "Array":
  56153. if (urls.length === 0)
  56154. urls = urlOrArrayBuffer;
  56155. // If we found a supported format, we load it immediately and stop the loop
  56156. for (var i = 0; i < urls.length; i++) {
  56157. var url = urls[i];
  56158. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56159. codecSupportedFound = true;
  56160. }
  56161. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56162. codecSupportedFound = true;
  56163. }
  56164. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56165. codecSupportedFound = true;
  56166. }
  56167. if (url.indexOf("blob:") !== -1) {
  56168. codecSupportedFound = true;
  56169. }
  56170. if (codecSupportedFound) {
  56171. // Loading sound using XHR2
  56172. if (!this._streaming) {
  56173. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56174. }
  56175. else {
  56176. this._htmlAudioElement = new Audio(url);
  56177. this._htmlAudioElement.controls = false;
  56178. this._htmlAudioElement.loop = this.loop;
  56179. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56180. this._htmlAudioElement.preload = "auto";
  56181. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56182. _this._isReadyToPlay = true;
  56183. if (_this.autoplay) {
  56184. _this.play();
  56185. }
  56186. if (_this._readyToPlayCallback) {
  56187. _this._readyToPlayCallback();
  56188. }
  56189. });
  56190. document.body.appendChild(this._htmlAudioElement);
  56191. }
  56192. break;
  56193. }
  56194. }
  56195. break;
  56196. default:
  56197. validParameter = false;
  56198. break;
  56199. }
  56200. if (!validParameter) {
  56201. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56202. }
  56203. else {
  56204. if (!codecSupportedFound) {
  56205. this._isReadyToPlay = true;
  56206. // Simulating a ready to play event to avoid breaking code path
  56207. if (this._readyToPlayCallback) {
  56208. window.setTimeout(function () {
  56209. if (_this._readyToPlayCallback) {
  56210. _this._readyToPlayCallback();
  56211. }
  56212. }, 1000);
  56213. }
  56214. }
  56215. }
  56216. }
  56217. }
  56218. else {
  56219. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56220. this._scene.mainSoundTrack.AddSound(this);
  56221. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56222. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56223. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56224. }
  56225. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56226. if (this._readyToPlayCallback) {
  56227. window.setTimeout(function () {
  56228. if (_this._readyToPlayCallback) {
  56229. _this._readyToPlayCallback();
  56230. }
  56231. }, 1000);
  56232. }
  56233. }
  56234. }
  56235. Sound.prototype.dispose = function () {
  56236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56237. if (this.isPlaying) {
  56238. this.stop();
  56239. }
  56240. this._isReadyToPlay = false;
  56241. if (this.soundTrackId === -1) {
  56242. this._scene.mainSoundTrack.RemoveSound(this);
  56243. }
  56244. else {
  56245. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56246. }
  56247. if (this._soundGain) {
  56248. this._soundGain.disconnect();
  56249. this._soundGain = null;
  56250. }
  56251. if (this._soundPanner) {
  56252. this._soundPanner.disconnect();
  56253. this._soundPanner = null;
  56254. }
  56255. if (this._soundSource) {
  56256. this._soundSource.disconnect();
  56257. this._soundSource = null;
  56258. }
  56259. this._audioBuffer = null;
  56260. if (this._htmlAudioElement) {
  56261. this._htmlAudioElement.pause();
  56262. this._htmlAudioElement.src = "";
  56263. document.body.removeChild(this._htmlAudioElement);
  56264. }
  56265. if (this._connectedMesh && this._registerFunc) {
  56266. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56267. this._connectedMesh = null;
  56268. }
  56269. }
  56270. };
  56271. Sound.prototype.isReady = function () {
  56272. return this._isReadyToPlay;
  56273. };
  56274. Sound.prototype._soundLoaded = function (audioData) {
  56275. var _this = this;
  56276. if (!BABYLON.Engine.audioEngine.audioContext) {
  56277. return;
  56278. }
  56279. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56280. _this._audioBuffer = buffer;
  56281. _this._isReadyToPlay = true;
  56282. if (_this.autoplay) {
  56283. _this.play();
  56284. }
  56285. if (_this._readyToPlayCallback) {
  56286. _this._readyToPlayCallback();
  56287. }
  56288. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56289. };
  56290. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56292. this._audioBuffer = audioBuffer;
  56293. this._isReadyToPlay = true;
  56294. }
  56295. };
  56296. Sound.prototype.updateOptions = function (options) {
  56297. if (options) {
  56298. this.loop = options.loop || this.loop;
  56299. this.maxDistance = options.maxDistance || this.maxDistance;
  56300. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56301. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56302. this.refDistance = options.refDistance || this.refDistance;
  56303. this.distanceModel = options.distanceModel || this.distanceModel;
  56304. this._playbackRate = options.playbackRate || this._playbackRate;
  56305. this._updateSpatialParameters();
  56306. if (this.isPlaying) {
  56307. if (this._streaming) {
  56308. this._htmlAudioElement.playbackRate = this._playbackRate;
  56309. }
  56310. else {
  56311. if (this._soundSource) {
  56312. this._soundSource.playbackRate.value = this._playbackRate;
  56313. }
  56314. }
  56315. }
  56316. }
  56317. };
  56318. Sound.prototype._createSpatialParameters = function () {
  56319. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56320. if (this._scene.headphone) {
  56321. this._panningModel = "HRTF";
  56322. }
  56323. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56324. this._updateSpatialParameters();
  56325. this._soundPanner.connect(this._ouputAudioNode);
  56326. this._inputAudioNode = this._soundPanner;
  56327. }
  56328. };
  56329. Sound.prototype._updateSpatialParameters = function () {
  56330. if (this.spatialSound && this._soundPanner) {
  56331. if (this.useCustomAttenuation) {
  56332. // Tricks to disable in a way embedded Web Audio attenuation
  56333. this._soundPanner.distanceModel = "linear";
  56334. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56335. this._soundPanner.refDistance = 1;
  56336. this._soundPanner.rolloffFactor = 1;
  56337. this._soundPanner.panningModel = this._panningModel;
  56338. }
  56339. else {
  56340. this._soundPanner.distanceModel = this.distanceModel;
  56341. this._soundPanner.maxDistance = this.maxDistance;
  56342. this._soundPanner.refDistance = this.refDistance;
  56343. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56344. this._soundPanner.panningModel = this._panningModel;
  56345. }
  56346. }
  56347. };
  56348. Sound.prototype.switchPanningModelToHRTF = function () {
  56349. this._panningModel = "HRTF";
  56350. this._switchPanningModel();
  56351. };
  56352. Sound.prototype.switchPanningModelToEqualPower = function () {
  56353. this._panningModel = "equalpower";
  56354. this._switchPanningModel();
  56355. };
  56356. Sound.prototype._switchPanningModel = function () {
  56357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56358. this._soundPanner.panningModel = this._panningModel;
  56359. }
  56360. };
  56361. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56362. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56363. if (this._isOutputConnected) {
  56364. this._ouputAudioNode.disconnect();
  56365. }
  56366. this._ouputAudioNode.connect(soundTrackAudioNode);
  56367. this._isOutputConnected = true;
  56368. }
  56369. };
  56370. /**
  56371. * Transform this sound into a directional source
  56372. * @param coneInnerAngle Size of the inner cone in degree
  56373. * @param coneOuterAngle Size of the outer cone in degree
  56374. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56375. */
  56376. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56377. if (coneOuterAngle < coneInnerAngle) {
  56378. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56379. return;
  56380. }
  56381. this._coneInnerAngle = coneInnerAngle;
  56382. this._coneOuterAngle = coneOuterAngle;
  56383. this._coneOuterGain = coneOuterGain;
  56384. this._isDirectional = true;
  56385. if (this.isPlaying && this.loop) {
  56386. this.stop();
  56387. this.play();
  56388. }
  56389. };
  56390. Sound.prototype.setPosition = function (newPosition) {
  56391. this._position = newPosition;
  56392. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56393. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56394. }
  56395. };
  56396. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56397. this._localDirection = newLocalDirection;
  56398. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56399. this._updateDirection();
  56400. }
  56401. };
  56402. Sound.prototype._updateDirection = function () {
  56403. if (!this._connectedMesh || !this._soundPanner) {
  56404. return;
  56405. }
  56406. var mat = this._connectedMesh.getWorldMatrix();
  56407. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56408. direction.normalize();
  56409. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56410. };
  56411. Sound.prototype.updateDistanceFromListener = function () {
  56412. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56413. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56414. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56415. }
  56416. };
  56417. Sound.prototype.setAttenuationFunction = function (callback) {
  56418. this._customAttenuationFunction = callback;
  56419. };
  56420. /**
  56421. * Play the sound
  56422. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56423. * @param offset (optional) Start the sound setting it at a specific time
  56424. */
  56425. Sound.prototype.play = function (time, offset) {
  56426. var _this = this;
  56427. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56428. try {
  56429. if (this._startOffset < 0) {
  56430. time = -this._startOffset;
  56431. this._startOffset = 0;
  56432. }
  56433. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56434. if (!this._soundSource || !this._streamingSource) {
  56435. if (this.spatialSound && this._soundPanner) {
  56436. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56437. if (this._isDirectional) {
  56438. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56439. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56440. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56441. if (this._connectedMesh) {
  56442. this._updateDirection();
  56443. }
  56444. else {
  56445. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56446. }
  56447. }
  56448. }
  56449. }
  56450. if (this._streaming) {
  56451. if (!this._streamingSource) {
  56452. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56453. this._htmlAudioElement.onended = function () { _this._onended(); };
  56454. this._htmlAudioElement.playbackRate = this._playbackRate;
  56455. }
  56456. this._streamingSource.disconnect();
  56457. this._streamingSource.connect(this._inputAudioNode);
  56458. this._htmlAudioElement.play();
  56459. }
  56460. else {
  56461. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56462. this._soundSource.buffer = this._audioBuffer;
  56463. this._soundSource.connect(this._inputAudioNode);
  56464. this._soundSource.loop = this.loop;
  56465. this._soundSource.playbackRate.value = this._playbackRate;
  56466. this._soundSource.onended = function () { _this._onended(); };
  56467. if (this._soundSource.buffer) {
  56468. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56469. }
  56470. }
  56471. this._startTime = startTime;
  56472. this.isPlaying = true;
  56473. this.isPaused = false;
  56474. }
  56475. catch (ex) {
  56476. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56477. }
  56478. }
  56479. };
  56480. Sound.prototype._onended = function () {
  56481. this.isPlaying = false;
  56482. if (this.onended) {
  56483. this.onended();
  56484. }
  56485. };
  56486. /**
  56487. * Stop the sound
  56488. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56489. */
  56490. Sound.prototype.stop = function (time) {
  56491. if (this.isPlaying) {
  56492. if (this._streaming) {
  56493. this._htmlAudioElement.pause();
  56494. // Test needed for Firefox or it will generate an Invalid State Error
  56495. if (this._htmlAudioElement.currentTime > 0) {
  56496. this._htmlAudioElement.currentTime = 0;
  56497. }
  56498. }
  56499. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56500. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56501. this._soundSource.stop(stopTime);
  56502. this._soundSource.onended = function () { };
  56503. if (!this.isPaused) {
  56504. this._startOffset = 0;
  56505. }
  56506. }
  56507. this.isPlaying = false;
  56508. }
  56509. };
  56510. Sound.prototype.pause = function () {
  56511. if (this.isPlaying) {
  56512. this.isPaused = true;
  56513. if (this._streaming) {
  56514. this._htmlAudioElement.pause();
  56515. }
  56516. else if (BABYLON.Engine.audioEngine.audioContext) {
  56517. this.stop(0);
  56518. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56519. }
  56520. }
  56521. };
  56522. Sound.prototype.setVolume = function (newVolume, time) {
  56523. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56524. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56525. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56526. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56527. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56528. }
  56529. else {
  56530. this._soundGain.gain.value = newVolume;
  56531. }
  56532. }
  56533. this._volume = newVolume;
  56534. };
  56535. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56536. this._playbackRate = newPlaybackRate;
  56537. if (this.isPlaying) {
  56538. if (this._streaming) {
  56539. this._htmlAudioElement.playbackRate = this._playbackRate;
  56540. }
  56541. else if (this._soundSource) {
  56542. this._soundSource.playbackRate.value = this._playbackRate;
  56543. }
  56544. }
  56545. };
  56546. Sound.prototype.getVolume = function () {
  56547. return this._volume;
  56548. };
  56549. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56550. var _this = this;
  56551. if (this._connectedMesh && this._registerFunc) {
  56552. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56553. this._registerFunc = null;
  56554. }
  56555. this._connectedMesh = meshToConnectTo;
  56556. if (!this.spatialSound) {
  56557. this.spatialSound = true;
  56558. this._createSpatialParameters();
  56559. if (this.isPlaying && this.loop) {
  56560. this.stop();
  56561. this.play();
  56562. }
  56563. }
  56564. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56565. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56566. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56567. };
  56568. Sound.prototype.detachFromMesh = function () {
  56569. if (this._connectedMesh && this._registerFunc) {
  56570. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56571. this._registerFunc = null;
  56572. this._connectedMesh = null;
  56573. }
  56574. };
  56575. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56576. if (!node.getBoundingInfo) {
  56577. return;
  56578. }
  56579. var mesh = node;
  56580. var boundingInfo = mesh.getBoundingInfo();
  56581. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56582. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56583. this._updateDirection();
  56584. }
  56585. };
  56586. Sound.prototype.clone = function () {
  56587. var _this = this;
  56588. if (!this._streaming) {
  56589. var setBufferAndRun = function () {
  56590. if (_this._isReadyToPlay) {
  56591. clonedSound._audioBuffer = _this.getAudioBuffer();
  56592. clonedSound._isReadyToPlay = true;
  56593. if (clonedSound.autoplay) {
  56594. clonedSound.play();
  56595. }
  56596. }
  56597. else {
  56598. window.setTimeout(setBufferAndRun, 300);
  56599. }
  56600. };
  56601. var currentOptions = {
  56602. autoplay: this.autoplay, loop: this.loop,
  56603. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56604. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56605. refDistance: this.refDistance, distanceModel: this.distanceModel
  56606. };
  56607. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56608. if (this.useCustomAttenuation) {
  56609. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56610. }
  56611. clonedSound.setPosition(this._position);
  56612. clonedSound.setPlaybackRate(this._playbackRate);
  56613. setBufferAndRun();
  56614. return clonedSound;
  56615. }
  56616. else {
  56617. return null;
  56618. }
  56619. };
  56620. Sound.prototype.getAudioBuffer = function () {
  56621. return this._audioBuffer;
  56622. };
  56623. Sound.prototype.serialize = function () {
  56624. var serializationObject = {
  56625. name: this.name,
  56626. url: this.name,
  56627. autoplay: this.autoplay,
  56628. loop: this.loop,
  56629. volume: this._volume,
  56630. spatialSound: this.spatialSound,
  56631. maxDistance: this.maxDistance,
  56632. rolloffFactor: this.rolloffFactor,
  56633. refDistance: this.refDistance,
  56634. distanceModel: this.distanceModel,
  56635. playbackRate: this._playbackRate,
  56636. panningModel: this._panningModel,
  56637. soundTrackId: this.soundTrackId
  56638. };
  56639. if (this.spatialSound) {
  56640. if (this._connectedMesh)
  56641. serializationObject.connectedMeshId = this._connectedMesh.id;
  56642. serializationObject.position = this._position.asArray();
  56643. serializationObject.refDistance = this.refDistance;
  56644. serializationObject.distanceModel = this.distanceModel;
  56645. serializationObject.isDirectional = this._isDirectional;
  56646. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56647. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56648. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56649. serializationObject.coneOuterGain = this._coneOuterGain;
  56650. }
  56651. return serializationObject;
  56652. };
  56653. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56654. var soundName = parsedSound.name;
  56655. var soundUrl;
  56656. if (parsedSound.url) {
  56657. soundUrl = rootUrl + parsedSound.url;
  56658. }
  56659. else {
  56660. soundUrl = rootUrl + soundName;
  56661. }
  56662. var options = {
  56663. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56664. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56665. rolloffFactor: parsedSound.rolloffFactor,
  56666. refDistance: parsedSound.refDistance,
  56667. distanceModel: parsedSound.distanceModel,
  56668. playbackRate: parsedSound.playbackRate
  56669. };
  56670. var newSound;
  56671. if (!sourceSound) {
  56672. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56673. scene._addPendingData(newSound);
  56674. }
  56675. else {
  56676. var setBufferAndRun = function () {
  56677. if (sourceSound._isReadyToPlay) {
  56678. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56679. newSound._isReadyToPlay = true;
  56680. if (newSound.autoplay) {
  56681. newSound.play();
  56682. }
  56683. }
  56684. else {
  56685. window.setTimeout(setBufferAndRun, 300);
  56686. }
  56687. };
  56688. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56689. setBufferAndRun();
  56690. }
  56691. if (parsedSound.position) {
  56692. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56693. newSound.setPosition(soundPosition);
  56694. }
  56695. if (parsedSound.isDirectional) {
  56696. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56697. if (parsedSound.localDirectionToMesh) {
  56698. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56699. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56700. }
  56701. }
  56702. if (parsedSound.connectedMeshId) {
  56703. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56704. if (connectedMesh) {
  56705. newSound.attachToMesh(connectedMesh);
  56706. }
  56707. }
  56708. return newSound;
  56709. };
  56710. return Sound;
  56711. }());
  56712. BABYLON.Sound = Sound;
  56713. })(BABYLON || (BABYLON = {}));
  56714. //# sourceMappingURL=babylon.sound.js.map
  56715. var BABYLON;
  56716. (function (BABYLON) {
  56717. var SoundTrack = /** @class */ (function () {
  56718. function SoundTrack(scene, options) {
  56719. this.id = -1;
  56720. this._isMainTrack = false;
  56721. this._isInitialized = false;
  56722. this._scene = scene;
  56723. this.soundCollection = new Array();
  56724. this._options = options;
  56725. if (!this._isMainTrack) {
  56726. this._scene.soundTracks.push(this);
  56727. this.id = this._scene.soundTracks.length - 1;
  56728. }
  56729. }
  56730. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56731. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56732. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56733. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56734. if (this._options) {
  56735. if (this._options.volume) {
  56736. this._outputAudioNode.gain.value = this._options.volume;
  56737. }
  56738. if (this._options.mainTrack) {
  56739. this._isMainTrack = this._options.mainTrack;
  56740. }
  56741. }
  56742. this._isInitialized = true;
  56743. }
  56744. };
  56745. SoundTrack.prototype.dispose = function () {
  56746. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56747. if (this._connectedAnalyser) {
  56748. this._connectedAnalyser.stopDebugCanvas();
  56749. }
  56750. while (this.soundCollection.length) {
  56751. this.soundCollection[0].dispose();
  56752. }
  56753. if (this._outputAudioNode) {
  56754. this._outputAudioNode.disconnect();
  56755. }
  56756. this._outputAudioNode = null;
  56757. }
  56758. };
  56759. SoundTrack.prototype.AddSound = function (sound) {
  56760. if (!this._isInitialized) {
  56761. this._initializeSoundTrackAudioGraph();
  56762. }
  56763. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56764. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56765. }
  56766. if (sound.soundTrackId) {
  56767. if (sound.soundTrackId === -1) {
  56768. this._scene.mainSoundTrack.RemoveSound(sound);
  56769. }
  56770. else {
  56771. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56772. }
  56773. }
  56774. this.soundCollection.push(sound);
  56775. sound.soundTrackId = this.id;
  56776. };
  56777. SoundTrack.prototype.RemoveSound = function (sound) {
  56778. var index = this.soundCollection.indexOf(sound);
  56779. if (index !== -1) {
  56780. this.soundCollection.splice(index, 1);
  56781. }
  56782. };
  56783. SoundTrack.prototype.setVolume = function (newVolume) {
  56784. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56785. this._outputAudioNode.gain.value = newVolume;
  56786. }
  56787. };
  56788. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56789. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56790. for (var i = 0; i < this.soundCollection.length; i++) {
  56791. this.soundCollection[i].switchPanningModelToHRTF();
  56792. }
  56793. }
  56794. };
  56795. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56797. for (var i = 0; i < this.soundCollection.length; i++) {
  56798. this.soundCollection[i].switchPanningModelToEqualPower();
  56799. }
  56800. }
  56801. };
  56802. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56803. if (this._connectedAnalyser) {
  56804. this._connectedAnalyser.stopDebugCanvas();
  56805. }
  56806. this._connectedAnalyser = analyser;
  56807. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56808. this._outputAudioNode.disconnect();
  56809. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56810. }
  56811. };
  56812. return SoundTrack;
  56813. }());
  56814. BABYLON.SoundTrack = SoundTrack;
  56815. })(BABYLON || (BABYLON = {}));
  56816. //# sourceMappingURL=babylon.soundtrack.js.map
  56817. var BABYLON;
  56818. (function (BABYLON) {
  56819. var Analyser = /** @class */ (function () {
  56820. function Analyser(scene) {
  56821. this.SMOOTHING = 0.75;
  56822. this.FFT_SIZE = 512;
  56823. this.BARGRAPHAMPLITUDE = 256;
  56824. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56825. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56826. this._scene = scene;
  56827. this._audioEngine = BABYLON.Engine.audioEngine;
  56828. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56829. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56830. this._webAudioAnalyser.minDecibels = -140;
  56831. this._webAudioAnalyser.maxDecibels = 0;
  56832. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56833. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56834. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56835. }
  56836. }
  56837. Analyser.prototype.getFrequencyBinCount = function () {
  56838. if (this._audioEngine.canUseWebAudio) {
  56839. return this._webAudioAnalyser.frequencyBinCount;
  56840. }
  56841. else {
  56842. return 0;
  56843. }
  56844. };
  56845. Analyser.prototype.getByteFrequencyData = function () {
  56846. if (this._audioEngine.canUseWebAudio) {
  56847. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56848. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56849. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56850. }
  56851. return this._byteFreqs;
  56852. };
  56853. Analyser.prototype.getByteTimeDomainData = function () {
  56854. if (this._audioEngine.canUseWebAudio) {
  56855. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56856. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56857. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56858. }
  56859. return this._byteTime;
  56860. };
  56861. Analyser.prototype.getFloatFrequencyData = function () {
  56862. if (this._audioEngine.canUseWebAudio) {
  56863. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56864. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56865. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56866. }
  56867. return this._floatFreqs;
  56868. };
  56869. Analyser.prototype.drawDebugCanvas = function () {
  56870. var _this = this;
  56871. if (this._audioEngine.canUseWebAudio) {
  56872. if (!this._debugCanvas) {
  56873. this._debugCanvas = document.createElement("canvas");
  56874. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56875. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56876. this._debugCanvas.style.position = "absolute";
  56877. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56878. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56879. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56880. document.body.appendChild(this._debugCanvas);
  56881. this._registerFunc = function () {
  56882. _this.drawDebugCanvas();
  56883. };
  56884. this._scene.registerBeforeRender(this._registerFunc);
  56885. }
  56886. if (this._registerFunc && this._debugCanvasContext) {
  56887. var workingArray = this.getByteFrequencyData();
  56888. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56889. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56890. // Draw the frequency domain chart.
  56891. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56892. var value = workingArray[i];
  56893. var percent = value / this.BARGRAPHAMPLITUDE;
  56894. var height = this.DEBUGCANVASSIZE.height * percent;
  56895. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56896. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56897. var hue = i / this.getFrequencyBinCount() * 360;
  56898. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56899. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56900. }
  56901. }
  56902. }
  56903. };
  56904. Analyser.prototype.stopDebugCanvas = function () {
  56905. if (this._debugCanvas) {
  56906. if (this._registerFunc) {
  56907. this._scene.unregisterBeforeRender(this._registerFunc);
  56908. this._registerFunc = null;
  56909. }
  56910. document.body.removeChild(this._debugCanvas);
  56911. this._debugCanvas = null;
  56912. this._debugCanvasContext = null;
  56913. }
  56914. };
  56915. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56916. if (this._audioEngine.canUseWebAudio) {
  56917. inputAudioNode.connect(this._webAudioAnalyser);
  56918. this._webAudioAnalyser.connect(outputAudioNode);
  56919. }
  56920. };
  56921. Analyser.prototype.dispose = function () {
  56922. if (this._audioEngine.canUseWebAudio) {
  56923. this._webAudioAnalyser.disconnect();
  56924. }
  56925. };
  56926. return Analyser;
  56927. }());
  56928. BABYLON.Analyser = Analyser;
  56929. })(BABYLON || (BABYLON = {}));
  56930. //# sourceMappingURL=babylon.analyser.js.map
  56931. var BABYLON;
  56932. (function (BABYLON) {
  56933. var CubeTexture = /** @class */ (function (_super) {
  56934. __extends(CubeTexture, _super);
  56935. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56936. if (extensions === void 0) { extensions = null; }
  56937. if (noMipmap === void 0) { noMipmap = false; }
  56938. if (files === void 0) { files = null; }
  56939. if (onLoad === void 0) { onLoad = null; }
  56940. if (onError === void 0) { onError = null; }
  56941. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56942. if (prefiltered === void 0) { prefiltered = false; }
  56943. if (forcedExtension === void 0) { forcedExtension = null; }
  56944. var _this = _super.call(this, scene) || this;
  56945. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56946. /**
  56947. * Gets or sets the center of the bounding box associated with the cube texture
  56948. * It must define where the camera used to render the texture was set
  56949. */
  56950. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56951. _this.name = rootUrl;
  56952. _this.url = rootUrl;
  56953. _this._noMipmap = noMipmap;
  56954. _this.hasAlpha = false;
  56955. _this._format = format;
  56956. _this._prefiltered = prefiltered;
  56957. _this.isCube = true;
  56958. _this._textureMatrix = BABYLON.Matrix.Identity();
  56959. if (prefiltered) {
  56960. _this.gammaSpace = false;
  56961. }
  56962. if (!rootUrl && !files) {
  56963. return _this;
  56964. }
  56965. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56966. var lastDot = rootUrl.lastIndexOf(".");
  56967. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56968. var isDDS = (extension === ".dds");
  56969. if (!files) {
  56970. if (!isDDS && !extensions) {
  56971. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56972. }
  56973. files = [];
  56974. if (extensions) {
  56975. for (var index = 0; index < extensions.length; index++) {
  56976. files.push(rootUrl + extensions[index]);
  56977. }
  56978. }
  56979. }
  56980. _this._files = files;
  56981. if (!_this._texture) {
  56982. if (!scene.useDelayedTextureLoading) {
  56983. if (prefiltered) {
  56984. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56985. }
  56986. else {
  56987. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56988. }
  56989. }
  56990. else {
  56991. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56992. }
  56993. }
  56994. else if (onLoad) {
  56995. if (_this._texture.isReady) {
  56996. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56997. }
  56998. else {
  56999. _this._texture.onLoadedObservable.add(onLoad);
  57000. }
  57001. }
  57002. return _this;
  57003. }
  57004. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57005. get: function () {
  57006. return this._boundingBoxSize;
  57007. },
  57008. /**
  57009. * Gets or sets the size of the bounding box associated with the cube texture
  57010. * When defined, the cubemap will switch to local mode
  57011. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57012. * @example https://www.babylonjs-playground.com/#RNASML
  57013. */
  57014. set: function (value) {
  57015. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57016. return;
  57017. }
  57018. this._boundingBoxSize = value;
  57019. var scene = this.getScene();
  57020. if (scene) {
  57021. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57022. }
  57023. },
  57024. enumerable: true,
  57025. configurable: true
  57026. });
  57027. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57028. var rootUrlKey = "";
  57029. files.forEach(function (url) { return rootUrlKey += url; });
  57030. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57031. };
  57032. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57033. if (forcedExtension === void 0) { forcedExtension = null; }
  57034. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57035. };
  57036. // Methods
  57037. CubeTexture.prototype.delayLoad = function () {
  57038. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57039. return;
  57040. }
  57041. var scene = this.getScene();
  57042. if (!scene) {
  57043. return;
  57044. }
  57045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57046. this._texture = this._getFromCache(this.url, this._noMipmap);
  57047. if (!this._texture) {
  57048. if (this._prefiltered) {
  57049. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57050. }
  57051. else {
  57052. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57053. }
  57054. }
  57055. };
  57056. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57057. return this._textureMatrix;
  57058. };
  57059. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57060. this._textureMatrix = value;
  57061. };
  57062. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57063. var texture = BABYLON.SerializationHelper.Parse(function () {
  57064. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57065. }, parsedTexture, scene);
  57066. // Local Cubemaps
  57067. if (parsedTexture.boundingBoxPosition) {
  57068. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57069. }
  57070. if (parsedTexture.boundingBoxSize) {
  57071. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57072. }
  57073. // Animations
  57074. if (parsedTexture.animations) {
  57075. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57076. var parsedAnimation = parsedTexture.animations[animationIndex];
  57077. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57078. }
  57079. }
  57080. return texture;
  57081. };
  57082. CubeTexture.prototype.clone = function () {
  57083. var _this = this;
  57084. return BABYLON.SerializationHelper.Clone(function () {
  57085. var scene = _this.getScene();
  57086. if (!scene) {
  57087. return _this;
  57088. }
  57089. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57090. }, this);
  57091. };
  57092. return CubeTexture;
  57093. }(BABYLON.BaseTexture));
  57094. BABYLON.CubeTexture = CubeTexture;
  57095. })(BABYLON || (BABYLON = {}));
  57096. //# sourceMappingURL=babylon.cubeTexture.js.map
  57097. var BABYLON;
  57098. (function (BABYLON) {
  57099. var RenderTargetTexture = /** @class */ (function (_super) {
  57100. __extends(RenderTargetTexture, _super);
  57101. /**
  57102. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57103. * or used a shadow, depth texture...
  57104. * @param name The friendly name of the texture
  57105. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  57106. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57107. * @param generateMipMaps True if mip maps need to be generated after render.
  57108. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57109. * @param type The type of the buffer in the RTT (int, half float, float...)
  57110. * @param isCube True if a cube texture needs to be created
  57111. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57112. * @param generateDepthBuffer True to generate a depth buffer
  57113. * @param generateStencilBuffer True to generate a stencil buffer
  57114. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57115. */
  57116. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57117. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57118. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57119. if (isCube === void 0) { isCube = false; }
  57120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57121. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57122. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57123. if (isMulti === void 0) { isMulti = false; }
  57124. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57125. _this.isCube = isCube;
  57126. /**
  57127. * Use this list to define the list of mesh you want to render.
  57128. */
  57129. _this.renderList = new Array();
  57130. _this.renderParticles = true;
  57131. _this.renderSprites = false;
  57132. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57133. _this.ignoreCameraViewport = false;
  57134. // Events
  57135. /**
  57136. * An event triggered when the texture is unbind.
  57137. * @type {BABYLON.Observable}
  57138. */
  57139. _this.onBeforeBindObservable = new BABYLON.Observable();
  57140. /**
  57141. * An event triggered when the texture is unbind.
  57142. * @type {BABYLON.Observable}
  57143. */
  57144. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57145. /**
  57146. * An event triggered before rendering the texture
  57147. * @type {BABYLON.Observable}
  57148. */
  57149. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57150. /**
  57151. * An event triggered after rendering the texture
  57152. * @type {BABYLON.Observable}
  57153. */
  57154. _this.onAfterRenderObservable = new BABYLON.Observable();
  57155. /**
  57156. * An event triggered after the texture clear
  57157. * @type {BABYLON.Observable}
  57158. */
  57159. _this.onClearObservable = new BABYLON.Observable();
  57160. _this._currentRefreshId = -1;
  57161. _this._refreshRate = 1;
  57162. _this._samples = 1;
  57163. /**
  57164. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57165. * It must define where the camera used to render the texture is set
  57166. */
  57167. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57168. scene = _this.getScene();
  57169. if (!scene) {
  57170. return _this;
  57171. }
  57172. _this._engine = scene.getEngine();
  57173. _this.name = name;
  57174. _this.isRenderTarget = true;
  57175. _this._initialSizeParameter = size;
  57176. _this._processSizeParameter(size);
  57177. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57178. });
  57179. _this._generateMipMaps = generateMipMaps ? true : false;
  57180. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57181. // Rendering groups
  57182. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57183. if (isMulti) {
  57184. return _this;
  57185. }
  57186. _this._renderTargetOptions = {
  57187. generateMipMaps: generateMipMaps,
  57188. type: type,
  57189. samplingMode: samplingMode,
  57190. generateDepthBuffer: generateDepthBuffer,
  57191. generateStencilBuffer: generateStencilBuffer
  57192. };
  57193. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57194. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57195. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57196. }
  57197. if (isCube) {
  57198. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57199. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57200. _this._textureMatrix = BABYLON.Matrix.Identity();
  57201. }
  57202. else {
  57203. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57204. }
  57205. return _this;
  57206. }
  57207. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57208. get: function () {
  57209. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57210. },
  57211. enumerable: true,
  57212. configurable: true
  57213. });
  57214. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57215. get: function () {
  57216. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57217. },
  57218. enumerable: true,
  57219. configurable: true
  57220. });
  57221. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57222. get: function () {
  57223. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57224. },
  57225. enumerable: true,
  57226. configurable: true
  57227. });
  57228. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57229. set: function (callback) {
  57230. if (this._onAfterUnbindObserver) {
  57231. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57232. }
  57233. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57234. },
  57235. enumerable: true,
  57236. configurable: true
  57237. });
  57238. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57239. set: function (callback) {
  57240. if (this._onBeforeRenderObserver) {
  57241. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57242. }
  57243. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57244. },
  57245. enumerable: true,
  57246. configurable: true
  57247. });
  57248. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57249. set: function (callback) {
  57250. if (this._onAfterRenderObserver) {
  57251. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57252. }
  57253. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57254. },
  57255. enumerable: true,
  57256. configurable: true
  57257. });
  57258. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57259. set: function (callback) {
  57260. if (this._onClearObserver) {
  57261. this.onClearObservable.remove(this._onClearObserver);
  57262. }
  57263. this._onClearObserver = this.onClearObservable.add(callback);
  57264. },
  57265. enumerable: true,
  57266. configurable: true
  57267. });
  57268. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57269. get: function () {
  57270. return this._renderTargetOptions;
  57271. },
  57272. enumerable: true,
  57273. configurable: true
  57274. });
  57275. RenderTargetTexture.prototype._onRatioRescale = function () {
  57276. if (this._sizeRatio) {
  57277. this.resize(this._initialSizeParameter);
  57278. }
  57279. };
  57280. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57281. get: function () {
  57282. return this._boundingBoxSize;
  57283. },
  57284. /**
  57285. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57286. * When defined, the cubemap will switch to local mode
  57287. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57288. * @example https://www.babylonjs-playground.com/#RNASML
  57289. */
  57290. set: function (value) {
  57291. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57292. return;
  57293. }
  57294. this._boundingBoxSize = value;
  57295. var scene = this.getScene();
  57296. if (scene) {
  57297. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57298. }
  57299. },
  57300. enumerable: true,
  57301. configurable: true
  57302. });
  57303. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57304. if (size.ratio) {
  57305. this._sizeRatio = size.ratio;
  57306. this._size = {
  57307. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57308. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57309. };
  57310. }
  57311. else {
  57312. this._size = size;
  57313. }
  57314. };
  57315. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57316. get: function () {
  57317. return this._samples;
  57318. },
  57319. set: function (value) {
  57320. if (this._samples === value) {
  57321. return;
  57322. }
  57323. var scene = this.getScene();
  57324. if (!scene) {
  57325. return;
  57326. }
  57327. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57328. },
  57329. enumerable: true,
  57330. configurable: true
  57331. });
  57332. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57333. this._currentRefreshId = -1;
  57334. };
  57335. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57336. get: function () {
  57337. return this._refreshRate;
  57338. },
  57339. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57340. set: function (value) {
  57341. this._refreshRate = value;
  57342. this.resetRefreshCounter();
  57343. },
  57344. enumerable: true,
  57345. configurable: true
  57346. });
  57347. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57348. if (!this._postProcessManager) {
  57349. var scene = this.getScene();
  57350. if (!scene) {
  57351. return;
  57352. }
  57353. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57354. this._postProcesses = new Array();
  57355. }
  57356. this._postProcesses.push(postProcess);
  57357. this._postProcesses[0].autoClear = false;
  57358. };
  57359. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57360. if (!this._postProcesses) {
  57361. return;
  57362. }
  57363. if (dispose) {
  57364. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57365. var postProcess = _a[_i];
  57366. postProcess.dispose();
  57367. }
  57368. }
  57369. this._postProcesses = [];
  57370. };
  57371. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57372. if (!this._postProcesses) {
  57373. return;
  57374. }
  57375. var index = this._postProcesses.indexOf(postProcess);
  57376. if (index === -1) {
  57377. return;
  57378. }
  57379. this._postProcesses.splice(index, 1);
  57380. if (this._postProcesses.length > 0) {
  57381. this._postProcesses[0].autoClear = false;
  57382. }
  57383. };
  57384. RenderTargetTexture.prototype._shouldRender = function () {
  57385. if (this._currentRefreshId === -1) {
  57386. this._currentRefreshId = 1;
  57387. return true;
  57388. }
  57389. if (this.refreshRate === this._currentRefreshId) {
  57390. this._currentRefreshId = 1;
  57391. return true;
  57392. }
  57393. this._currentRefreshId++;
  57394. return false;
  57395. };
  57396. RenderTargetTexture.prototype.getRenderSize = function () {
  57397. if (this._size.width) {
  57398. return this._size.width;
  57399. }
  57400. return this._size;
  57401. };
  57402. RenderTargetTexture.prototype.getRenderWidth = function () {
  57403. if (this._size.width) {
  57404. return this._size.width;
  57405. }
  57406. return this._size;
  57407. };
  57408. RenderTargetTexture.prototype.getRenderHeight = function () {
  57409. if (this._size.width) {
  57410. return this._size.height;
  57411. }
  57412. return this._size;
  57413. };
  57414. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57415. get: function () {
  57416. return true;
  57417. },
  57418. enumerable: true,
  57419. configurable: true
  57420. });
  57421. RenderTargetTexture.prototype.scale = function (ratio) {
  57422. var newSize = this.getRenderSize() * ratio;
  57423. this.resize(newSize);
  57424. };
  57425. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57426. if (this.isCube) {
  57427. return this._textureMatrix;
  57428. }
  57429. return _super.prototype.getReflectionTextureMatrix.call(this);
  57430. };
  57431. RenderTargetTexture.prototype.resize = function (size) {
  57432. this.releaseInternalTexture();
  57433. var scene = this.getScene();
  57434. if (!scene) {
  57435. return;
  57436. }
  57437. this._processSizeParameter(size);
  57438. if (this.isCube) {
  57439. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57440. }
  57441. else {
  57442. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57443. }
  57444. };
  57445. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57446. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57447. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57448. var scene = this.getScene();
  57449. if (!scene) {
  57450. return;
  57451. }
  57452. var engine = scene.getEngine();
  57453. if (this.useCameraPostProcesses !== undefined) {
  57454. useCameraPostProcess = this.useCameraPostProcesses;
  57455. }
  57456. if (this._waitingRenderList) {
  57457. this.renderList = [];
  57458. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57459. var id = this._waitingRenderList[index];
  57460. var mesh_1 = scene.getMeshByID(id);
  57461. if (mesh_1) {
  57462. this.renderList.push(mesh_1);
  57463. }
  57464. }
  57465. delete this._waitingRenderList;
  57466. }
  57467. // Is predicate defined?
  57468. if (this.renderListPredicate) {
  57469. if (this.renderList) {
  57470. this.renderList.splice(0); // Clear previous renderList
  57471. }
  57472. else {
  57473. this.renderList = [];
  57474. }
  57475. var scene = this.getScene();
  57476. if (!scene) {
  57477. return;
  57478. }
  57479. var sceneMeshes = scene.meshes;
  57480. for (var index = 0; index < sceneMeshes.length; index++) {
  57481. var mesh = sceneMeshes[index];
  57482. if (this.renderListPredicate(mesh)) {
  57483. this.renderList.push(mesh);
  57484. }
  57485. }
  57486. }
  57487. this.onBeforeBindObservable.notifyObservers(this);
  57488. // Set custom projection.
  57489. // Needs to be before binding to prevent changing the aspect ratio.
  57490. var camera;
  57491. if (this.activeCamera) {
  57492. camera = this.activeCamera;
  57493. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57494. if (this.activeCamera !== scene.activeCamera) {
  57495. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57496. }
  57497. }
  57498. else {
  57499. camera = scene.activeCamera;
  57500. if (camera) {
  57501. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57502. }
  57503. }
  57504. // Prepare renderingManager
  57505. this._renderingManager.reset();
  57506. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57507. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57508. var sceneRenderId = scene.getRenderId();
  57509. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57510. var mesh = currentRenderList[meshIndex];
  57511. if (mesh) {
  57512. if (!mesh.isReady()) {
  57513. // Reset _currentRefreshId
  57514. this.resetRefreshCounter();
  57515. continue;
  57516. }
  57517. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57518. var isMasked = void 0;
  57519. if (!this.renderList && camera) {
  57520. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57521. }
  57522. else {
  57523. isMasked = false;
  57524. }
  57525. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57526. mesh._activate(sceneRenderId);
  57527. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57528. var subMesh = mesh.subMeshes[subIndex];
  57529. scene._activeIndices.addCount(subMesh.indexCount, false);
  57530. this._renderingManager.dispatch(subMesh, mesh);
  57531. }
  57532. }
  57533. }
  57534. }
  57535. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57536. var particleSystem = scene.particleSystems[particleIndex];
  57537. var emitter = particleSystem.emitter;
  57538. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57539. continue;
  57540. }
  57541. if (currentRenderList.indexOf(emitter) >= 0) {
  57542. this._renderingManager.dispatchParticles(particleSystem);
  57543. }
  57544. }
  57545. if (this.isCube) {
  57546. for (var face = 0; face < 6; face++) {
  57547. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57548. scene.incrementRenderId();
  57549. scene.resetCachedMaterial();
  57550. }
  57551. }
  57552. else {
  57553. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57554. }
  57555. this.onAfterUnbindObservable.notifyObservers(this);
  57556. if (scene.activeCamera) {
  57557. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57558. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57559. }
  57560. engine.setViewport(scene.activeCamera.viewport);
  57561. }
  57562. scene.resetCachedMaterial();
  57563. };
  57564. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57565. var minimum = 128;
  57566. var x = renderDimension * scale;
  57567. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57568. // Ensure we don't exceed the render dimension (while staying POT)
  57569. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57570. };
  57571. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57572. var _this = this;
  57573. if (!this._texture) {
  57574. return;
  57575. }
  57576. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57577. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57578. });
  57579. };
  57580. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57581. var scene = this.getScene();
  57582. if (!scene) {
  57583. return;
  57584. }
  57585. var engine = scene.getEngine();
  57586. if (!this._texture) {
  57587. return;
  57588. }
  57589. // Bind
  57590. if (this._postProcessManager) {
  57591. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57592. }
  57593. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57594. if (this._texture) {
  57595. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57596. }
  57597. }
  57598. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57599. // Clear
  57600. if (this.onClearObservable.hasObservers()) {
  57601. this.onClearObservable.notifyObservers(engine);
  57602. }
  57603. else {
  57604. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57605. }
  57606. if (!this._doNotChangeAspectRatio) {
  57607. scene.updateTransformMatrix(true);
  57608. }
  57609. // Render
  57610. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57611. if (this._postProcessManager) {
  57612. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57613. }
  57614. else if (useCameraPostProcess) {
  57615. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57616. }
  57617. if (!this._doNotChangeAspectRatio) {
  57618. scene.updateTransformMatrix(true);
  57619. }
  57620. // Dump ?
  57621. if (dumpForDebug) {
  57622. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57623. }
  57624. // Unbind
  57625. if (!this.isCube || faceIndex === 5) {
  57626. if (this.isCube) {
  57627. if (faceIndex === 5) {
  57628. engine.generateMipMapsForCubemap(this._texture);
  57629. }
  57630. }
  57631. this.unbindFrameBuffer(engine, faceIndex);
  57632. }
  57633. else {
  57634. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57635. }
  57636. };
  57637. /**
  57638. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57639. * This allowed control for front to back rendering or reversly depending of the special needs.
  57640. *
  57641. * @param renderingGroupId The rendering group id corresponding to its index
  57642. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57643. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57644. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57645. */
  57646. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57647. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57648. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57649. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57650. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57651. };
  57652. /**
  57653. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57654. *
  57655. * @param renderingGroupId The rendering group id corresponding to its index
  57656. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57657. */
  57658. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57659. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57660. };
  57661. RenderTargetTexture.prototype.clone = function () {
  57662. var textureSize = this.getSize();
  57663. 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);
  57664. // Base texture
  57665. newTexture.hasAlpha = this.hasAlpha;
  57666. newTexture.level = this.level;
  57667. // RenderTarget Texture
  57668. newTexture.coordinatesMode = this.coordinatesMode;
  57669. if (this.renderList) {
  57670. newTexture.renderList = this.renderList.slice(0);
  57671. }
  57672. return newTexture;
  57673. };
  57674. RenderTargetTexture.prototype.serialize = function () {
  57675. if (!this.name) {
  57676. return null;
  57677. }
  57678. var serializationObject = _super.prototype.serialize.call(this);
  57679. serializationObject.renderTargetSize = this.getRenderSize();
  57680. serializationObject.renderList = [];
  57681. if (this.renderList) {
  57682. for (var index = 0; index < this.renderList.length; index++) {
  57683. serializationObject.renderList.push(this.renderList[index].id);
  57684. }
  57685. }
  57686. return serializationObject;
  57687. };
  57688. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57689. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57690. var objBuffer = this.getInternalTexture();
  57691. var scene = this.getScene();
  57692. if (objBuffer && scene) {
  57693. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57694. }
  57695. };
  57696. RenderTargetTexture.prototype.dispose = function () {
  57697. if (this._postProcessManager) {
  57698. this._postProcessManager.dispose();
  57699. this._postProcessManager = null;
  57700. }
  57701. this.clearPostProcesses(true);
  57702. if (this._resizeObserver) {
  57703. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57704. this._resizeObserver = null;
  57705. }
  57706. this.renderList = null;
  57707. // Remove from custom render targets
  57708. var scene = this.getScene();
  57709. if (!scene) {
  57710. return;
  57711. }
  57712. var index = scene.customRenderTargets.indexOf(this);
  57713. if (index >= 0) {
  57714. scene.customRenderTargets.splice(index, 1);
  57715. }
  57716. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57717. var camera = _a[_i];
  57718. index = camera.customRenderTargets.indexOf(this);
  57719. if (index >= 0) {
  57720. camera.customRenderTargets.splice(index, 1);
  57721. }
  57722. }
  57723. _super.prototype.dispose.call(this);
  57724. };
  57725. RenderTargetTexture.prototype._rebuild = function () {
  57726. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57727. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57728. }
  57729. if (this._postProcessManager) {
  57730. this._postProcessManager._rebuild();
  57731. }
  57732. };
  57733. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57734. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57735. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57736. return RenderTargetTexture;
  57737. }(BABYLON.Texture));
  57738. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57739. })(BABYLON || (BABYLON = {}));
  57740. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57741. var BABYLON;
  57742. (function (BABYLON) {
  57743. ;
  57744. var MultiRenderTarget = /** @class */ (function (_super) {
  57745. __extends(MultiRenderTarget, _super);
  57746. function MultiRenderTarget(name, size, count, scene, options) {
  57747. var _this = this;
  57748. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57749. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57750. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57751. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57752. _this._engine = scene.getEngine();
  57753. if (!_this.isSupported) {
  57754. _this.dispose();
  57755. return;
  57756. }
  57757. var types = [];
  57758. var samplingModes = [];
  57759. for (var i = 0; i < count; i++) {
  57760. if (options && options.types && options.types[i] !== undefined) {
  57761. types.push(options.types[i]);
  57762. }
  57763. else {
  57764. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57765. }
  57766. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57767. samplingModes.push(options.samplingModes[i]);
  57768. }
  57769. else {
  57770. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57771. }
  57772. }
  57773. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57774. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57775. _this._size = size;
  57776. _this._multiRenderTargetOptions = {
  57777. samplingModes: samplingModes,
  57778. generateMipMaps: generateMipMaps,
  57779. generateDepthBuffer: generateDepthBuffer,
  57780. generateStencilBuffer: generateStencilBuffer,
  57781. generateDepthTexture: generateDepthTexture,
  57782. types: types,
  57783. textureCount: count
  57784. };
  57785. _this._createInternalTextures();
  57786. _this._createTextures();
  57787. return _this;
  57788. }
  57789. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57790. get: function () {
  57791. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57792. },
  57793. enumerable: true,
  57794. configurable: true
  57795. });
  57796. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57797. get: function () {
  57798. return this._textures;
  57799. },
  57800. enumerable: true,
  57801. configurable: true
  57802. });
  57803. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57804. get: function () {
  57805. return this._textures[this._textures.length - 1];
  57806. },
  57807. enumerable: true,
  57808. configurable: true
  57809. });
  57810. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57811. set: function (wrap) {
  57812. if (this._textures) {
  57813. for (var i = 0; i < this._textures.length; i++) {
  57814. this._textures[i].wrapU = wrap;
  57815. }
  57816. }
  57817. },
  57818. enumerable: true,
  57819. configurable: true
  57820. });
  57821. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57822. set: function (wrap) {
  57823. if (this._textures) {
  57824. for (var i = 0; i < this._textures.length; i++) {
  57825. this._textures[i].wrapV = wrap;
  57826. }
  57827. }
  57828. },
  57829. enumerable: true,
  57830. configurable: true
  57831. });
  57832. MultiRenderTarget.prototype._rebuild = function () {
  57833. this.releaseInternalTextures();
  57834. this._createInternalTextures();
  57835. for (var i = 0; i < this._internalTextures.length; i++) {
  57836. var texture = this._textures[i];
  57837. texture._texture = this._internalTextures[i];
  57838. }
  57839. // Keeps references to frame buffer and stencil/depth buffer
  57840. this._texture = this._internalTextures[0];
  57841. };
  57842. MultiRenderTarget.prototype._createInternalTextures = function () {
  57843. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57844. };
  57845. MultiRenderTarget.prototype._createTextures = function () {
  57846. this._textures = [];
  57847. for (var i = 0; i < this._internalTextures.length; i++) {
  57848. var texture = new BABYLON.Texture(null, this.getScene());
  57849. texture._texture = this._internalTextures[i];
  57850. this._textures.push(texture);
  57851. }
  57852. // Keeps references to frame buffer and stencil/depth buffer
  57853. this._texture = this._internalTextures[0];
  57854. };
  57855. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57856. get: function () {
  57857. return this._samples;
  57858. },
  57859. set: function (value) {
  57860. if (this._samples === value) {
  57861. return;
  57862. }
  57863. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57864. },
  57865. enumerable: true,
  57866. configurable: true
  57867. });
  57868. MultiRenderTarget.prototype.resize = function (size) {
  57869. this.releaseInternalTextures();
  57870. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57871. this._createInternalTextures();
  57872. };
  57873. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57874. var _this = this;
  57875. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57876. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57877. });
  57878. };
  57879. MultiRenderTarget.prototype.dispose = function () {
  57880. this.releaseInternalTextures();
  57881. _super.prototype.dispose.call(this);
  57882. };
  57883. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57884. if (!this._internalTextures) {
  57885. return;
  57886. }
  57887. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57888. if (this._internalTextures[i] !== undefined) {
  57889. this._internalTextures[i].dispose();
  57890. this._internalTextures.splice(i, 1);
  57891. }
  57892. }
  57893. };
  57894. return MultiRenderTarget;
  57895. }(BABYLON.RenderTargetTexture));
  57896. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57897. })(BABYLON || (BABYLON = {}));
  57898. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57899. var BABYLON;
  57900. (function (BABYLON) {
  57901. var MirrorTexture = /** @class */ (function (_super) {
  57902. __extends(MirrorTexture, _super);
  57903. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57904. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57906. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57907. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57908. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57909. _this._transformMatrix = BABYLON.Matrix.Zero();
  57910. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57911. _this._adaptiveBlurKernel = 0;
  57912. _this._blurKernelX = 0;
  57913. _this._blurKernelY = 0;
  57914. _this._blurRatio = 1.0;
  57915. _this.ignoreCameraViewport = true;
  57916. _this.onBeforeRenderObservable.add(function () {
  57917. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57918. _this._savedViewMatrix = scene.getViewMatrix();
  57919. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57920. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57921. scene.clipPlane = _this.mirrorPlane;
  57922. scene.getEngine().cullBackFaces = false;
  57923. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57924. });
  57925. _this.onAfterRenderObservable.add(function () {
  57926. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57927. scene.getEngine().cullBackFaces = true;
  57928. scene._mirroredCameraPosition = null;
  57929. delete scene.clipPlane;
  57930. });
  57931. return _this;
  57932. }
  57933. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57934. get: function () {
  57935. return this._blurRatio;
  57936. },
  57937. set: function (value) {
  57938. if (this._blurRatio === value) {
  57939. return;
  57940. }
  57941. this._blurRatio = value;
  57942. this._preparePostProcesses();
  57943. },
  57944. enumerable: true,
  57945. configurable: true
  57946. });
  57947. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57948. set: function (value) {
  57949. this._adaptiveBlurKernel = value;
  57950. this._autoComputeBlurKernel();
  57951. },
  57952. enumerable: true,
  57953. configurable: true
  57954. });
  57955. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57956. set: function (value) {
  57957. this.blurKernelX = value;
  57958. this.blurKernelY = value;
  57959. },
  57960. enumerable: true,
  57961. configurable: true
  57962. });
  57963. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57964. get: function () {
  57965. return this._blurKernelX;
  57966. },
  57967. set: function (value) {
  57968. if (this._blurKernelX === value) {
  57969. return;
  57970. }
  57971. this._blurKernelX = value;
  57972. this._preparePostProcesses();
  57973. },
  57974. enumerable: true,
  57975. configurable: true
  57976. });
  57977. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57978. get: function () {
  57979. return this._blurKernelY;
  57980. },
  57981. set: function (value) {
  57982. if (this._blurKernelY === value) {
  57983. return;
  57984. }
  57985. this._blurKernelY = value;
  57986. this._preparePostProcesses();
  57987. },
  57988. enumerable: true,
  57989. configurable: true
  57990. });
  57991. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57992. var engine = this.getScene().getEngine();
  57993. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57994. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57995. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57996. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57997. };
  57998. MirrorTexture.prototype._onRatioRescale = function () {
  57999. if (this._sizeRatio) {
  58000. this.resize(this._initialSizeParameter);
  58001. if (!this._adaptiveBlurKernel) {
  58002. this._preparePostProcesses();
  58003. }
  58004. }
  58005. if (this._adaptiveBlurKernel) {
  58006. this._autoComputeBlurKernel();
  58007. }
  58008. };
  58009. MirrorTexture.prototype._preparePostProcesses = function () {
  58010. this.clearPostProcesses(true);
  58011. if (this._blurKernelX && this._blurKernelY) {
  58012. var engine = this.getScene().getEngine();
  58013. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58014. 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);
  58015. this._blurX.autoClear = false;
  58016. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58017. this._blurX.inputTexture = this._texture;
  58018. }
  58019. else {
  58020. this._blurX.alwaysForcePOT = true;
  58021. }
  58022. 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);
  58023. this._blurY.autoClear = false;
  58024. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58025. this.addPostProcess(this._blurX);
  58026. this.addPostProcess(this._blurY);
  58027. }
  58028. else {
  58029. if (this._blurY) {
  58030. this.removePostProcess(this._blurY);
  58031. this._blurY.dispose();
  58032. this._blurY = null;
  58033. }
  58034. if (this._blurX) {
  58035. this.removePostProcess(this._blurX);
  58036. this._blurX.dispose();
  58037. this._blurX = null;
  58038. }
  58039. }
  58040. };
  58041. MirrorTexture.prototype.clone = function () {
  58042. var scene = this.getScene();
  58043. if (!scene) {
  58044. return this;
  58045. }
  58046. var textureSize = this.getSize();
  58047. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58048. // Base texture
  58049. newTexture.hasAlpha = this.hasAlpha;
  58050. newTexture.level = this.level;
  58051. // Mirror Texture
  58052. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58053. if (this.renderList) {
  58054. newTexture.renderList = this.renderList.slice(0);
  58055. }
  58056. return newTexture;
  58057. };
  58058. MirrorTexture.prototype.serialize = function () {
  58059. if (!this.name) {
  58060. return null;
  58061. }
  58062. var serializationObject = _super.prototype.serialize.call(this);
  58063. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58064. return serializationObject;
  58065. };
  58066. return MirrorTexture;
  58067. }(BABYLON.RenderTargetTexture));
  58068. BABYLON.MirrorTexture = MirrorTexture;
  58069. })(BABYLON || (BABYLON = {}));
  58070. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58071. var BABYLON;
  58072. (function (BABYLON) {
  58073. /**
  58074. * Creates a refraction texture used by refraction channel of the standard material.
  58075. * @param name the texture name
  58076. * @param size size of the underlying texture
  58077. * @param scene root scene
  58078. */
  58079. var RefractionTexture = /** @class */ (function (_super) {
  58080. __extends(RefractionTexture, _super);
  58081. function RefractionTexture(name, size, scene, generateMipMaps) {
  58082. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58083. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58084. _this.depth = 2.0;
  58085. _this.onBeforeRenderObservable.add(function () {
  58086. scene.clipPlane = _this.refractionPlane;
  58087. });
  58088. _this.onAfterRenderObservable.add(function () {
  58089. delete scene.clipPlane;
  58090. });
  58091. return _this;
  58092. }
  58093. RefractionTexture.prototype.clone = function () {
  58094. var scene = this.getScene();
  58095. if (!scene) {
  58096. return this;
  58097. }
  58098. var textureSize = this.getSize();
  58099. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58100. // Base texture
  58101. newTexture.hasAlpha = this.hasAlpha;
  58102. newTexture.level = this.level;
  58103. // Refraction Texture
  58104. newTexture.refractionPlane = this.refractionPlane.clone();
  58105. if (this.renderList) {
  58106. newTexture.renderList = this.renderList.slice(0);
  58107. }
  58108. newTexture.depth = this.depth;
  58109. return newTexture;
  58110. };
  58111. RefractionTexture.prototype.serialize = function () {
  58112. if (!this.name) {
  58113. return null;
  58114. }
  58115. var serializationObject = _super.prototype.serialize.call(this);
  58116. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58117. serializationObject.depth = this.depth;
  58118. return serializationObject;
  58119. };
  58120. return RefractionTexture;
  58121. }(BABYLON.RenderTargetTexture));
  58122. BABYLON.RefractionTexture = RefractionTexture;
  58123. })(BABYLON || (BABYLON = {}));
  58124. //# sourceMappingURL=babylon.refractionTexture.js.map
  58125. var BABYLON;
  58126. (function (BABYLON) {
  58127. var DynamicTexture = /** @class */ (function (_super) {
  58128. __extends(DynamicTexture, _super);
  58129. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58130. if (scene === void 0) { scene = null; }
  58131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58132. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58133. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58134. _this.name = name;
  58135. _this._engine = _this.getScene().getEngine();
  58136. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58137. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58138. _this._generateMipMaps = generateMipMaps;
  58139. if (options.getContext) {
  58140. _this._canvas = options;
  58141. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58142. }
  58143. else {
  58144. _this._canvas = document.createElement("canvas");
  58145. if (options.width) {
  58146. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58147. }
  58148. else {
  58149. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58150. }
  58151. }
  58152. var textureSize = _this.getSize();
  58153. _this._canvas.width = textureSize.width;
  58154. _this._canvas.height = textureSize.height;
  58155. _this._context = _this._canvas.getContext("2d");
  58156. return _this;
  58157. }
  58158. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58159. get: function () {
  58160. return true;
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. DynamicTexture.prototype._recreate = function (textureSize) {
  58166. this._canvas.width = textureSize.width;
  58167. this._canvas.height = textureSize.height;
  58168. this.releaseInternalTexture();
  58169. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58170. };
  58171. DynamicTexture.prototype.scale = function (ratio) {
  58172. var textureSize = this.getSize();
  58173. textureSize.width *= ratio;
  58174. textureSize.height *= ratio;
  58175. this._recreate(textureSize);
  58176. };
  58177. DynamicTexture.prototype.scaleTo = function (width, height) {
  58178. var textureSize = this.getSize();
  58179. textureSize.width = width;
  58180. textureSize.height = height;
  58181. this._recreate(textureSize);
  58182. };
  58183. DynamicTexture.prototype.getContext = function () {
  58184. return this._context;
  58185. };
  58186. DynamicTexture.prototype.clear = function () {
  58187. var size = this.getSize();
  58188. this._context.fillRect(0, 0, size.width, size.height);
  58189. };
  58190. DynamicTexture.prototype.update = function (invertY) {
  58191. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58192. };
  58193. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58194. if (update === void 0) { update = true; }
  58195. var size = this.getSize();
  58196. if (clearColor) {
  58197. this._context.fillStyle = clearColor;
  58198. this._context.fillRect(0, 0, size.width, size.height);
  58199. }
  58200. this._context.font = font;
  58201. if (x === null || x === undefined) {
  58202. var textSize = this._context.measureText(text);
  58203. x = (size.width - textSize.width) / 2;
  58204. }
  58205. if (y === null || y === undefined) {
  58206. var fontSize = parseInt((font.replace(/\D/g, '')));
  58207. ;
  58208. y = (size.height / 2) + (fontSize / 3.65);
  58209. }
  58210. this._context.fillStyle = color;
  58211. this._context.fillText(text, x, y);
  58212. if (update) {
  58213. this.update(invertY);
  58214. }
  58215. };
  58216. DynamicTexture.prototype.clone = function () {
  58217. var scene = this.getScene();
  58218. if (!scene) {
  58219. return this;
  58220. }
  58221. var textureSize = this.getSize();
  58222. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58223. // Base texture
  58224. newTexture.hasAlpha = this.hasAlpha;
  58225. newTexture.level = this.level;
  58226. // Dynamic Texture
  58227. newTexture.wrapU = this.wrapU;
  58228. newTexture.wrapV = this.wrapV;
  58229. return newTexture;
  58230. };
  58231. DynamicTexture.prototype._rebuild = function () {
  58232. this.update();
  58233. };
  58234. return DynamicTexture;
  58235. }(BABYLON.Texture));
  58236. BABYLON.DynamicTexture = DynamicTexture;
  58237. })(BABYLON || (BABYLON = {}));
  58238. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58239. var BABYLON;
  58240. (function (BABYLON) {
  58241. var VideoTexture = /** @class */ (function (_super) {
  58242. __extends(VideoTexture, _super);
  58243. /**
  58244. * Creates a video texture.
  58245. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58246. * @param {string | null} name optional name, will detect from video source, if not defined
  58247. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58248. * @param {BABYLON.Scene} scene is obviously the current scene.
  58249. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58250. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58251. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58252. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58253. */
  58254. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58255. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58256. if (invertY === void 0) { invertY = false; }
  58257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58258. if (settings === void 0) { settings = {
  58259. autoPlay: true,
  58260. loop: true,
  58261. autoUpdateTexture: true,
  58262. }; }
  58263. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58264. _this._createInternalTexture = function () {
  58265. if (_this._texture != null) {
  58266. return;
  58267. }
  58268. if (!_this._engine.needPOTTextures ||
  58269. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58270. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58271. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58272. }
  58273. else {
  58274. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58275. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58276. _this._generateMipMaps = false;
  58277. }
  58278. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58279. _this._texture.isReady = true;
  58280. _this._updateInternalTexture();
  58281. };
  58282. _this.reset = function () {
  58283. if (_this._texture == null) {
  58284. return;
  58285. }
  58286. _this._texture.dispose();
  58287. _this._texture = null;
  58288. };
  58289. _this._updateInternalTexture = function (e) {
  58290. if (_this._texture == null || !_this._texture.isReady) {
  58291. return;
  58292. }
  58293. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58294. return;
  58295. }
  58296. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58297. };
  58298. _this._engine = _this.getScene().getEngine();
  58299. _this._generateMipMaps = generateMipMaps;
  58300. _this._samplingMode = samplingMode;
  58301. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58302. _this.name = name || _this._getName(src);
  58303. _this.video = _this._getVideo(src);
  58304. if (settings.autoPlay !== undefined) {
  58305. _this.video.autoplay = settings.autoPlay;
  58306. }
  58307. if (settings.loop !== undefined) {
  58308. _this.video.loop = settings.loop;
  58309. }
  58310. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58311. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58312. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58313. _this.video.addEventListener("emptied", _this.reset);
  58314. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58315. _this._createInternalTexture();
  58316. }
  58317. return _this;
  58318. }
  58319. VideoTexture.prototype._getName = function (src) {
  58320. if (src instanceof HTMLVideoElement) {
  58321. return src.currentSrc;
  58322. }
  58323. if (typeof src === "object") {
  58324. return src.toString();
  58325. }
  58326. return src;
  58327. };
  58328. ;
  58329. VideoTexture.prototype._getVideo = function (src) {
  58330. if (src instanceof HTMLVideoElement) {
  58331. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58332. return src;
  58333. }
  58334. var video = document.createElement("video");
  58335. if (typeof src === "string") {
  58336. BABYLON.Tools.SetCorsBehavior(src, video);
  58337. video.src = src;
  58338. }
  58339. else {
  58340. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58341. src.forEach(function (url) {
  58342. var source = document.createElement("source");
  58343. source.src = url;
  58344. video.appendChild(source);
  58345. });
  58346. }
  58347. return video;
  58348. };
  58349. ;
  58350. /**
  58351. * Internal method to initiate `update`.
  58352. */
  58353. VideoTexture.prototype._rebuild = function () {
  58354. this.update();
  58355. };
  58356. /**
  58357. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58358. */
  58359. VideoTexture.prototype.update = function () {
  58360. if (!this.autoUpdateTexture) {
  58361. // Expecting user to call `updateTexture` manually
  58362. return;
  58363. }
  58364. this.updateTexture(true);
  58365. };
  58366. /**
  58367. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58368. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58369. */
  58370. VideoTexture.prototype.updateTexture = function (isVisible) {
  58371. if (!isVisible) {
  58372. return;
  58373. }
  58374. if (this.video.paused) {
  58375. return;
  58376. }
  58377. this._updateInternalTexture();
  58378. };
  58379. /**
  58380. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58381. * @param url New url.
  58382. */
  58383. VideoTexture.prototype.updateURL = function (url) {
  58384. this.video.src = url;
  58385. };
  58386. VideoTexture.prototype.dispose = function () {
  58387. _super.prototype.dispose.call(this);
  58388. this.video.removeEventListener("canplay", this._createInternalTexture);
  58389. this.video.removeEventListener("paused", this._updateInternalTexture);
  58390. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58391. this.video.removeEventListener("emptied", this.reset);
  58392. this.video.pause();
  58393. };
  58394. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58395. var video = document.createElement("video");
  58396. var constraintsDeviceId;
  58397. if (constraints && constraints.deviceId) {
  58398. constraintsDeviceId = {
  58399. exact: constraints.deviceId,
  58400. };
  58401. }
  58402. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58403. if (navigator.mediaDevices) {
  58404. navigator.mediaDevices.getUserMedia({ video: constraints })
  58405. .then(function (stream) {
  58406. if (video.mozSrcObject !== undefined) {
  58407. // hack for Firefox < 19
  58408. video.mozSrcObject = stream;
  58409. }
  58410. else {
  58411. video.srcObject = stream;
  58412. }
  58413. var onPlaying = function () {
  58414. if (onReady) {
  58415. onReady(new VideoTexture("video", video, scene, true, true));
  58416. }
  58417. video.removeEventListener("playing", onPlaying);
  58418. };
  58419. video.addEventListener("playing", onPlaying);
  58420. video.play();
  58421. })
  58422. .catch(function (err) {
  58423. BABYLON.Tools.Error(err.name);
  58424. });
  58425. }
  58426. else {
  58427. navigator.getUserMedia =
  58428. navigator.getUserMedia ||
  58429. navigator.webkitGetUserMedia ||
  58430. navigator.mozGetUserMedia ||
  58431. navigator.msGetUserMedia;
  58432. if (navigator.getUserMedia) {
  58433. navigator.getUserMedia({
  58434. video: {
  58435. deviceId: constraintsDeviceId,
  58436. width: {
  58437. min: (constraints && constraints.minWidth) || 256,
  58438. max: (constraints && constraints.maxWidth) || 640,
  58439. },
  58440. height: {
  58441. min: (constraints && constraints.minHeight) || 256,
  58442. max: (constraints && constraints.maxHeight) || 480,
  58443. },
  58444. },
  58445. }, function (stream) {
  58446. if (video.mozSrcObject !== undefined) {
  58447. // hack for Firefox < 19
  58448. video.mozSrcObject = stream;
  58449. }
  58450. else {
  58451. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58452. }
  58453. video.play();
  58454. if (onReady) {
  58455. onReady(new VideoTexture("video", video, scene, true, true));
  58456. }
  58457. }, function (e) {
  58458. BABYLON.Tools.Error(e.name);
  58459. });
  58460. }
  58461. }
  58462. };
  58463. return VideoTexture;
  58464. }(BABYLON.Texture));
  58465. BABYLON.VideoTexture = VideoTexture;
  58466. })(BABYLON || (BABYLON = {}));
  58467. //# sourceMappingURL=babylon.videoTexture.js.map
  58468. var BABYLON;
  58469. (function (BABYLON) {
  58470. var RawTexture = /** @class */ (function (_super) {
  58471. __extends(RawTexture, _super);
  58472. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58473. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58474. if (invertY === void 0) { invertY = false; }
  58475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58476. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58477. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58478. _this.format = format;
  58479. _this._engine = scene.getEngine();
  58480. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58481. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58482. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58483. return _this;
  58484. }
  58485. RawTexture.prototype.update = function (data) {
  58486. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58487. };
  58488. // Statics
  58489. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58491. if (invertY === void 0) { invertY = false; }
  58492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58493. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58494. };
  58495. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58496. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58497. if (invertY === void 0) { invertY = false; }
  58498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58499. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58500. };
  58501. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58503. if (invertY === void 0) { invertY = false; }
  58504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58505. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58506. };
  58507. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58509. if (invertY === void 0) { invertY = false; }
  58510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58511. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58513. };
  58514. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58516. if (invertY === void 0) { invertY = false; }
  58517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58518. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58519. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58520. };
  58521. return RawTexture;
  58522. }(BABYLON.Texture));
  58523. BABYLON.RawTexture = RawTexture;
  58524. })(BABYLON || (BABYLON = {}));
  58525. //# sourceMappingURL=babylon.rawTexture.js.map
  58526. var BABYLON;
  58527. (function (BABYLON) {
  58528. /**
  58529. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58530. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58531. */
  58532. var PostProcess = /** @class */ (function () {
  58533. /**
  58534. * Creates a new instance of @see PostProcess
  58535. * @param name The name of the PostProcess.
  58536. * @param fragmentUrl The url of the fragment shader to be used.
  58537. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58538. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58539. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58540. * @param camera The camera to apply the render pass to.
  58541. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58542. * @param engine The engine which the post process will be applied. (default: current engine)
  58543. * @param reusable If the post process can be reused on the same frame. (default: false)
  58544. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58545. * @param textureType Type of textures used when performing the post process. (default: 0)
  58546. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58547. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  58548. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58549. */
  58550. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58552. if (defines === void 0) { defines = null; }
  58553. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58554. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58555. if (blockCompilation === void 0) { blockCompilation = false; }
  58556. this.name = name;
  58557. /**
  58558. * Width of the texture to apply the post process on
  58559. */
  58560. this.width = -1;
  58561. /**
  58562. * Height of the texture to apply the post process on
  58563. */
  58564. this.height = -1;
  58565. /**
  58566. * If the buffer needs to be cleared before applying the post process. (default: true)
  58567. * Should be set to false if shader will overwrite all previous pixels.
  58568. */
  58569. this.autoClear = true;
  58570. /**
  58571. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58572. */
  58573. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58574. /**
  58575. * Animations to be used for the post processing
  58576. */
  58577. this.animations = new Array();
  58578. /**
  58579. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58580. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58581. */
  58582. this.enablePixelPerfectMode = false;
  58583. /**
  58584. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58585. */
  58586. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58587. /**
  58588. * Force textures to be a power of two (default: false)
  58589. */
  58590. this.alwaysForcePOT = false;
  58591. /**
  58592. * Number of sample textures (default: 1)
  58593. */
  58594. this.samples = 1;
  58595. /**
  58596. * Modify the scale of the post process to be the same as the viewport (default: false)
  58597. */
  58598. this.adaptScaleToCurrentViewport = false;
  58599. this._reusable = false;
  58600. /**
  58601. * Smart array of input and output textures for the post process.
  58602. */
  58603. this._textures = new BABYLON.SmartArray(2);
  58604. /**
  58605. * The index in _textures that corresponds to the output texture.
  58606. */
  58607. this._currentRenderTextureInd = 0;
  58608. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58609. this._texelSize = BABYLON.Vector2.Zero();
  58610. // Events
  58611. /**
  58612. * An event triggered when the postprocess is activated.
  58613. * @type {BABYLON.Observable}
  58614. */
  58615. this.onActivateObservable = new BABYLON.Observable();
  58616. /**
  58617. * An event triggered when the postprocess changes its size.
  58618. * @type {BABYLON.Observable}
  58619. */
  58620. this.onSizeChangedObservable = new BABYLON.Observable();
  58621. /**
  58622. * An event triggered when the postprocess applies its effect.
  58623. * @type {BABYLON.Observable}
  58624. */
  58625. this.onApplyObservable = new BABYLON.Observable();
  58626. /**
  58627. * An event triggered before rendering the postprocess
  58628. * @type {BABYLON.Observable}
  58629. */
  58630. this.onBeforeRenderObservable = new BABYLON.Observable();
  58631. /**
  58632. * An event triggered after rendering the postprocess
  58633. * @type {BABYLON.Observable}
  58634. */
  58635. this.onAfterRenderObservable = new BABYLON.Observable();
  58636. if (camera != null) {
  58637. this._camera = camera;
  58638. this._scene = camera.getScene();
  58639. camera.attachPostProcess(this);
  58640. this._engine = this._scene.getEngine();
  58641. this._scene.postProcesses.push(this);
  58642. }
  58643. else if (engine) {
  58644. this._engine = engine;
  58645. this._engine.postProcesses.push(this);
  58646. }
  58647. this._options = options;
  58648. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58649. this._reusable = reusable || false;
  58650. this._textureType = textureType;
  58651. this._samplers = samplers || [];
  58652. this._samplers.push("textureSampler");
  58653. this._fragmentUrl = fragmentUrl;
  58654. this._vertexUrl = vertexUrl;
  58655. this._parameters = parameters || [];
  58656. this._parameters.push("scale");
  58657. this._indexParameters = indexParameters;
  58658. if (!blockCompilation) {
  58659. this.updateEffect(defines);
  58660. }
  58661. }
  58662. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58663. /**
  58664. * A function that is added to the onActivateObservable
  58665. */
  58666. set: function (callback) {
  58667. if (this._onActivateObserver) {
  58668. this.onActivateObservable.remove(this._onActivateObserver);
  58669. }
  58670. if (callback) {
  58671. this._onActivateObserver = this.onActivateObservable.add(callback);
  58672. }
  58673. },
  58674. enumerable: true,
  58675. configurable: true
  58676. });
  58677. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58678. /**
  58679. * A function that is added to the onSizeChangedObservable
  58680. */
  58681. set: function (callback) {
  58682. if (this._onSizeChangedObserver) {
  58683. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58684. }
  58685. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58686. },
  58687. enumerable: true,
  58688. configurable: true
  58689. });
  58690. Object.defineProperty(PostProcess.prototype, "onApply", {
  58691. /**
  58692. * A function that is added to the onApplyObservable
  58693. */
  58694. set: function (callback) {
  58695. if (this._onApplyObserver) {
  58696. this.onApplyObservable.remove(this._onApplyObserver);
  58697. }
  58698. this._onApplyObserver = this.onApplyObservable.add(callback);
  58699. },
  58700. enumerable: true,
  58701. configurable: true
  58702. });
  58703. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58704. /**
  58705. * A function that is added to the onBeforeRenderObservable
  58706. */
  58707. set: function (callback) {
  58708. if (this._onBeforeRenderObserver) {
  58709. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58710. }
  58711. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58712. },
  58713. enumerable: true,
  58714. configurable: true
  58715. });
  58716. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58717. /**
  58718. * A function that is added to the onAfterRenderObservable
  58719. */
  58720. set: function (callback) {
  58721. if (this._onAfterRenderObserver) {
  58722. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58723. }
  58724. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58725. },
  58726. enumerable: true,
  58727. configurable: true
  58728. });
  58729. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58730. /**
  58731. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  58732. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58733. */
  58734. get: function () {
  58735. return this._textures.data[this._currentRenderTextureInd];
  58736. },
  58737. set: function (value) {
  58738. this._forcedOutputTexture = value;
  58739. },
  58740. enumerable: true,
  58741. configurable: true
  58742. });
  58743. /**
  58744. * Gets the camera which post process is applied to.
  58745. * @returns The camera the post process is applied to.
  58746. */
  58747. PostProcess.prototype.getCamera = function () {
  58748. return this._camera;
  58749. };
  58750. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58751. /**
  58752. * Gets the texel size of the postprocess.
  58753. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58754. */
  58755. get: function () {
  58756. if (this._shareOutputWithPostProcess) {
  58757. return this._shareOutputWithPostProcess.texelSize;
  58758. }
  58759. if (this._forcedOutputTexture) {
  58760. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58761. }
  58762. return this._texelSize;
  58763. },
  58764. enumerable: true,
  58765. configurable: true
  58766. });
  58767. /**
  58768. * Gets the engine which this post process belongs to.
  58769. * @returns The engine the post process was enabled with.
  58770. */
  58771. PostProcess.prototype.getEngine = function () {
  58772. return this._engine;
  58773. };
  58774. /**
  58775. * The effect that is created when initializing the post process.
  58776. * @returns The created effect corrisponding the the postprocess.
  58777. */
  58778. PostProcess.prototype.getEffect = function () {
  58779. return this._effect;
  58780. };
  58781. /**
  58782. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58783. * @param postProcess The post process to share the output with.
  58784. * @returns This post process.
  58785. */
  58786. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58787. this._disposeTextures();
  58788. this._shareOutputWithPostProcess = postProcess;
  58789. return this;
  58790. };
  58791. /**
  58792. * Updates the effect with the current post process compile time values and recompiles the shader.
  58793. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58794. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58795. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58796. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  58797. * @param onCompiled Called when the shader has been compiled.
  58798. * @param onError Called if there is an error when compiling a shader.
  58799. */
  58800. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58801. if (defines === void 0) { defines = null; }
  58802. if (uniforms === void 0) { uniforms = null; }
  58803. if (samplers === void 0) { samplers = null; }
  58804. 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);
  58805. };
  58806. /**
  58807. * The post process is reusable if it can be used multiple times within one frame.
  58808. * @returns If the post process is reusable
  58809. */
  58810. PostProcess.prototype.isReusable = function () {
  58811. return this._reusable;
  58812. };
  58813. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58814. PostProcess.prototype.markTextureDirty = function () {
  58815. this.width = -1;
  58816. };
  58817. /**
  58818. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58819. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  58820. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58821. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58822. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58823. */
  58824. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58825. var _this = this;
  58826. if (sourceTexture === void 0) { sourceTexture = null; }
  58827. camera = camera || this._camera;
  58828. var scene = camera.getScene();
  58829. var engine = scene.getEngine();
  58830. var maxSize = engine.getCaps().maxTextureSize;
  58831. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58832. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58833. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  58834. var webVRCamera = camera.parent;
  58835. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  58836. requiredWidth /= 2;
  58837. }
  58838. var desiredWidth = (this._options.width || requiredWidth);
  58839. var desiredHeight = this._options.height || requiredHeight;
  58840. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58841. if (this.adaptScaleToCurrentViewport) {
  58842. var currentViewport = engine.currentViewport;
  58843. if (currentViewport) {
  58844. desiredWidth *= currentViewport.width;
  58845. desiredHeight *= currentViewport.height;
  58846. }
  58847. }
  58848. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58849. if (!this._options.width) {
  58850. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58851. }
  58852. if (!this._options.height) {
  58853. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58854. }
  58855. }
  58856. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58857. if (this._textures.length > 0) {
  58858. for (var i = 0; i < this._textures.length; i++) {
  58859. this._engine._releaseTexture(this._textures.data[i]);
  58860. }
  58861. this._textures.reset();
  58862. }
  58863. this.width = desiredWidth;
  58864. this.height = desiredHeight;
  58865. var textureSize = { width: this.width, height: this.height };
  58866. var textureOptions = {
  58867. generateMipMaps: false,
  58868. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58869. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58870. samplingMode: this.renderTargetSamplingMode,
  58871. type: this._textureType
  58872. };
  58873. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58874. if (this._reusable) {
  58875. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58876. }
  58877. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58878. this.onSizeChangedObservable.notifyObservers(this);
  58879. }
  58880. this._textures.forEach(function (texture) {
  58881. if (texture.samples !== _this.samples) {
  58882. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58883. }
  58884. });
  58885. }
  58886. var target;
  58887. if (this._shareOutputWithPostProcess) {
  58888. target = this._shareOutputWithPostProcess.inputTexture;
  58889. }
  58890. else if (this._forcedOutputTexture) {
  58891. target = this._forcedOutputTexture;
  58892. this.width = this._forcedOutputTexture.width;
  58893. this.height = this._forcedOutputTexture.height;
  58894. }
  58895. else {
  58896. target = this.inputTexture;
  58897. }
  58898. // Bind the input of this post process to be used as the output of the previous post process.
  58899. if (this.enablePixelPerfectMode) {
  58900. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58901. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58902. }
  58903. else {
  58904. this._scaleRatio.copyFromFloats(1, 1);
  58905. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58906. }
  58907. this.onActivateObservable.notifyObservers(camera);
  58908. // Clear
  58909. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58910. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58911. }
  58912. if (this._reusable) {
  58913. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58914. }
  58915. };
  58916. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58917. /**
  58918. * If the post process is supported.
  58919. */
  58920. get: function () {
  58921. return this._effect.isSupported;
  58922. },
  58923. enumerable: true,
  58924. configurable: true
  58925. });
  58926. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58927. /**
  58928. * The aspect ratio of the output texture.
  58929. */
  58930. get: function () {
  58931. if (this._shareOutputWithPostProcess) {
  58932. return this._shareOutputWithPostProcess.aspectRatio;
  58933. }
  58934. if (this._forcedOutputTexture) {
  58935. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58936. }
  58937. return this.width / this.height;
  58938. },
  58939. enumerable: true,
  58940. configurable: true
  58941. });
  58942. /**
  58943. * Get a value indicating if the post-process is ready to be used
  58944. * @returns true if the post-process is ready (shader is compiled)
  58945. */
  58946. PostProcess.prototype.isReady = function () {
  58947. return this._effect && this._effect.isReady();
  58948. };
  58949. /**
  58950. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58951. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58952. */
  58953. PostProcess.prototype.apply = function () {
  58954. // Check
  58955. if (!this._effect || !this._effect.isReady())
  58956. return null;
  58957. // States
  58958. this._engine.enableEffect(this._effect);
  58959. this._engine.setState(false);
  58960. this._engine.setDepthBuffer(false);
  58961. this._engine.setDepthWrite(false);
  58962. // Alpha
  58963. this._engine.setAlphaMode(this.alphaMode);
  58964. if (this.alphaConstants) {
  58965. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58966. }
  58967. // Bind the output texture of the preivous post process as the input to this post process.
  58968. var source;
  58969. if (this._shareOutputWithPostProcess) {
  58970. source = this._shareOutputWithPostProcess.inputTexture;
  58971. }
  58972. else if (this._forcedOutputTexture) {
  58973. source = this._forcedOutputTexture;
  58974. }
  58975. else {
  58976. source = this.inputTexture;
  58977. }
  58978. this._effect._bindTexture("textureSampler", source);
  58979. // Parameters
  58980. this._effect.setVector2("scale", this._scaleRatio);
  58981. this.onApplyObservable.notifyObservers(this._effect);
  58982. return this._effect;
  58983. };
  58984. PostProcess.prototype._disposeTextures = function () {
  58985. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58986. return;
  58987. }
  58988. if (this._textures.length > 0) {
  58989. for (var i = 0; i < this._textures.length; i++) {
  58990. this._engine._releaseTexture(this._textures.data[i]);
  58991. }
  58992. }
  58993. this._textures.dispose();
  58994. };
  58995. /**
  58996. * Disposes the post process.
  58997. * @param camera The camera to dispose the post process on.
  58998. */
  58999. PostProcess.prototype.dispose = function (camera) {
  59000. camera = camera || this._camera;
  59001. this._disposeTextures();
  59002. if (this._scene) {
  59003. var index_1 = this._scene.postProcesses.indexOf(this);
  59004. if (index_1 !== -1) {
  59005. this._scene.postProcesses.splice(index_1, 1);
  59006. }
  59007. }
  59008. else {
  59009. var index_2 = this._engine.postProcesses.indexOf(this);
  59010. if (index_2 !== -1) {
  59011. this._engine.postProcesses.splice(index_2, 1);
  59012. }
  59013. }
  59014. if (!camera) {
  59015. return;
  59016. }
  59017. camera.detachPostProcess(this);
  59018. var index = camera._postProcesses.indexOf(this);
  59019. if (index === 0 && camera._postProcesses.length > 0) {
  59020. this._camera._postProcesses[0].markTextureDirty();
  59021. }
  59022. this.onActivateObservable.clear();
  59023. this.onAfterRenderObservable.clear();
  59024. this.onApplyObservable.clear();
  59025. this.onBeforeRenderObservable.clear();
  59026. this.onSizeChangedObservable.clear();
  59027. };
  59028. return PostProcess;
  59029. }());
  59030. BABYLON.PostProcess = PostProcess;
  59031. })(BABYLON || (BABYLON = {}));
  59032. //# sourceMappingURL=babylon.postProcess.js.map
  59033. var BABYLON;
  59034. (function (BABYLON) {
  59035. var PassPostProcess = /** @class */ (function (_super) {
  59036. __extends(PassPostProcess, _super);
  59037. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59038. if (camera === void 0) { camera = null; }
  59039. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59040. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59041. }
  59042. return PassPostProcess;
  59043. }(BABYLON.PostProcess));
  59044. BABYLON.PassPostProcess = PassPostProcess;
  59045. })(BABYLON || (BABYLON = {}));
  59046. //# sourceMappingURL=babylon.passPostProcess.js.map
  59047. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59048. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59049. s = arguments[i];
  59050. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59051. t[p] = s[p];
  59052. }
  59053. return t;
  59054. };
  59055. var BABYLON;
  59056. (function (BABYLON) {
  59057. /**
  59058. * Default implementation of @see IShadowGenerator.
  59059. * This is the main object responsible of generating shadows in the framework.
  59060. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59061. */
  59062. var ShadowGenerator = /** @class */ (function () {
  59063. /**
  59064. * Creates a ShadowGenerator object.
  59065. * A ShadowGenerator is the required tool to use the shadows.
  59066. * Each light casting shadows needs to use its own ShadowGenerator.
  59067. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59068. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59069. * @param light The light object generating the shadows.
  59070. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  59071. */
  59072. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59073. this._bias = 0.00005;
  59074. this._blurBoxOffset = 1;
  59075. this._blurScale = 2;
  59076. this._blurKernel = 1;
  59077. this._useKernelBlur = false;
  59078. this._filter = ShadowGenerator.FILTER_NONE;
  59079. this._darkness = 0;
  59080. this._transparencyShadow = false;
  59081. /**
  59082. * Controls the extent to which the shadows fade out at the edge of the frustum
  59083. * Used only by directionals and spots
  59084. */
  59085. this.frustumEdgeFalloff = 0;
  59086. /**
  59087. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59088. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59089. * It might on the other hand introduce peter panning.
  59090. */
  59091. this.forceBackFacesOnly = false;
  59092. this._lightDirection = BABYLON.Vector3.Zero();
  59093. this._viewMatrix = BABYLON.Matrix.Zero();
  59094. this._projectionMatrix = BABYLON.Matrix.Zero();
  59095. this._transformMatrix = BABYLON.Matrix.Zero();
  59096. this._currentFaceIndex = 0;
  59097. this._currentFaceIndexCache = 0;
  59098. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59099. this._mapSize = mapSize;
  59100. this._light = light;
  59101. this._scene = light.getScene();
  59102. light._shadowGenerator = this;
  59103. // Texture type fallback from float to int if not supported.
  59104. var caps = this._scene.getEngine().getCaps();
  59105. if (!useFullFloatFirst) {
  59106. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59107. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59108. }
  59109. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59110. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59111. }
  59112. else {
  59113. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59114. }
  59115. }
  59116. else {
  59117. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59118. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59119. }
  59120. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59121. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59122. }
  59123. else {
  59124. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59125. }
  59126. }
  59127. this._initializeGenerator();
  59128. }
  59129. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59130. /**
  59131. * Shadow generator mode None: no filtering applied.
  59132. */
  59133. get: function () {
  59134. return ShadowGenerator._FILTER_NONE;
  59135. },
  59136. enumerable: true,
  59137. configurable: true
  59138. });
  59139. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59140. /**
  59141. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59142. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59143. */
  59144. get: function () {
  59145. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59146. },
  59147. enumerable: true,
  59148. configurable: true
  59149. });
  59150. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59151. /**
  59152. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59153. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59154. */
  59155. get: function () {
  59156. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59157. },
  59158. enumerable: true,
  59159. configurable: true
  59160. });
  59161. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59162. /**
  59163. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59164. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59165. */
  59166. get: function () {
  59167. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59168. },
  59169. enumerable: true,
  59170. configurable: true
  59171. });
  59172. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59173. /**
  59174. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59175. * edge artifacts on steep falloff.
  59176. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59177. */
  59178. get: function () {
  59179. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59180. },
  59181. enumerable: true,
  59182. configurable: true
  59183. });
  59184. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59185. /**
  59186. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59187. * edge artifacts on steep falloff.
  59188. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59189. */
  59190. get: function () {
  59191. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59192. },
  59193. enumerable: true,
  59194. configurable: true
  59195. });
  59196. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59197. /**
  59198. * Gets the bias: offset applied on the depth preventing acnea.
  59199. */
  59200. get: function () {
  59201. return this._bias;
  59202. },
  59203. /**
  59204. * Sets the bias: offset applied on the depth preventing acnea.
  59205. */
  59206. set: function (bias) {
  59207. this._bias = bias;
  59208. },
  59209. enumerable: true,
  59210. configurable: true
  59211. });
  59212. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59213. /**
  59214. * Gets the blur box offset: offset applied during the blur pass.
  59215. * Only usefull if useKernelBlur = false
  59216. */
  59217. get: function () {
  59218. return this._blurBoxOffset;
  59219. },
  59220. /**
  59221. * Sets the blur box offset: offset applied during the blur pass.
  59222. * Only usefull if useKernelBlur = false
  59223. */
  59224. set: function (value) {
  59225. if (this._blurBoxOffset === value) {
  59226. return;
  59227. }
  59228. this._blurBoxOffset = value;
  59229. this._disposeBlurPostProcesses();
  59230. },
  59231. enumerable: true,
  59232. configurable: true
  59233. });
  59234. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59235. /**
  59236. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59237. * 2 means half of the size.
  59238. */
  59239. get: function () {
  59240. return this._blurScale;
  59241. },
  59242. /**
  59243. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59244. * 2 means half of the size.
  59245. */
  59246. set: function (value) {
  59247. if (this._blurScale === value) {
  59248. return;
  59249. }
  59250. this._blurScale = value;
  59251. this._disposeBlurPostProcesses();
  59252. },
  59253. enumerable: true,
  59254. configurable: true
  59255. });
  59256. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59257. /**
  59258. * Gets the blur kernel: kernel size of the blur pass.
  59259. * Only usefull if useKernelBlur = true
  59260. */
  59261. get: function () {
  59262. return this._blurKernel;
  59263. },
  59264. /**
  59265. * Sets the blur kernel: kernel size of the blur pass.
  59266. * Only usefull if useKernelBlur = true
  59267. */
  59268. set: function (value) {
  59269. if (this._blurKernel === value) {
  59270. return;
  59271. }
  59272. this._blurKernel = value;
  59273. this._disposeBlurPostProcesses();
  59274. },
  59275. enumerable: true,
  59276. configurable: true
  59277. });
  59278. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59279. /**
  59280. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59281. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59282. */
  59283. get: function () {
  59284. return this._useKernelBlur;
  59285. },
  59286. /**
  59287. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59288. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59289. */
  59290. set: function (value) {
  59291. if (this._useKernelBlur === value) {
  59292. return;
  59293. }
  59294. this._useKernelBlur = value;
  59295. this._disposeBlurPostProcesses();
  59296. },
  59297. enumerable: true,
  59298. configurable: true
  59299. });
  59300. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59301. /**
  59302. * Gets the depth scale used in ESM mode.
  59303. */
  59304. get: function () {
  59305. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59306. },
  59307. /**
  59308. * Sets the depth scale used in ESM mode.
  59309. * This can override the scale stored on the light.
  59310. */
  59311. set: function (value) {
  59312. this._depthScale = value;
  59313. },
  59314. enumerable: true,
  59315. configurable: true
  59316. });
  59317. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59318. /**
  59319. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59320. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59321. */
  59322. get: function () {
  59323. return this._filter;
  59324. },
  59325. /**
  59326. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59327. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59328. */
  59329. set: function (value) {
  59330. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59331. if (this._light.needCube()) {
  59332. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59333. this.useExponentialShadowMap = true;
  59334. return;
  59335. }
  59336. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59337. this.useCloseExponentialShadowMap = true;
  59338. return;
  59339. }
  59340. }
  59341. if (this._filter === value) {
  59342. return;
  59343. }
  59344. this._filter = value;
  59345. this._disposeBlurPostProcesses();
  59346. this._applyFilterValues();
  59347. this._light._markMeshesAsLightDirty();
  59348. },
  59349. enumerable: true,
  59350. configurable: true
  59351. });
  59352. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59353. /**
  59354. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59355. */
  59356. get: function () {
  59357. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59358. },
  59359. /**
  59360. * Sets the current filter to Poisson Sampling aka PCF.
  59361. */
  59362. set: function (value) {
  59363. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59364. return;
  59365. }
  59366. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59367. },
  59368. enumerable: true,
  59369. configurable: true
  59370. });
  59371. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59372. /**
  59373. * Gets if the current filter is set to VSM.
  59374. * DEPRECATED. Should use useExponentialShadowMap instead.
  59375. */
  59376. get: function () {
  59377. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59378. return this.useExponentialShadowMap;
  59379. },
  59380. /**
  59381. * Sets the current filter is to VSM.
  59382. * DEPRECATED. Should use useExponentialShadowMap instead.
  59383. */
  59384. set: function (value) {
  59385. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59386. this.useExponentialShadowMap = value;
  59387. },
  59388. enumerable: true,
  59389. configurable: true
  59390. });
  59391. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59392. /**
  59393. * Gets if the current filter is set to blurred VSM.
  59394. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59395. */
  59396. get: function () {
  59397. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59398. return this.useBlurExponentialShadowMap;
  59399. },
  59400. /**
  59401. * Sets the current filter is to blurred VSM.
  59402. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59403. */
  59404. set: function (value) {
  59405. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59406. this.useBlurExponentialShadowMap = value;
  59407. },
  59408. enumerable: true,
  59409. configurable: true
  59410. });
  59411. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59412. /**
  59413. * Gets if the current filter is set to ESM.
  59414. */
  59415. get: function () {
  59416. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59417. },
  59418. /**
  59419. * Sets the current filter is to ESM.
  59420. */
  59421. set: function (value) {
  59422. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59423. return;
  59424. }
  59425. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59426. },
  59427. enumerable: true,
  59428. configurable: true
  59429. });
  59430. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59431. /**
  59432. * Gets if the current filter is set to filtered ESM.
  59433. */
  59434. get: function () {
  59435. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59436. },
  59437. /**
  59438. * Gets if the current filter is set to filtered ESM.
  59439. */
  59440. set: function (value) {
  59441. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59442. return;
  59443. }
  59444. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59445. },
  59446. enumerable: true,
  59447. configurable: true
  59448. });
  59449. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59450. /**
  59451. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59452. * exponential to prevent steep falloff artifacts).
  59453. */
  59454. get: function () {
  59455. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59456. },
  59457. /**
  59458. * Sets the current filter to "close ESM" (using the inverse of the
  59459. * exponential to prevent steep falloff artifacts).
  59460. */
  59461. set: function (value) {
  59462. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59463. return;
  59464. }
  59465. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59466. },
  59467. enumerable: true,
  59468. configurable: true
  59469. });
  59470. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59471. /**
  59472. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59473. * exponential to prevent steep falloff artifacts).
  59474. */
  59475. get: function () {
  59476. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59477. },
  59478. /**
  59479. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59480. * exponential to prevent steep falloff artifacts).
  59481. */
  59482. set: function (value) {
  59483. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59484. return;
  59485. }
  59486. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59487. },
  59488. enumerable: true,
  59489. configurable: true
  59490. });
  59491. /**
  59492. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59493. * 0 means strongest and 1 would means no shadow.
  59494. * @returns the darkness.
  59495. */
  59496. ShadowGenerator.prototype.getDarkness = function () {
  59497. return this._darkness;
  59498. };
  59499. /**
  59500. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59501. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59502. * @returns the shadow generator allowing fluent coding.
  59503. */
  59504. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59505. if (darkness >= 1.0)
  59506. this._darkness = 1.0;
  59507. else if (darkness <= 0.0)
  59508. this._darkness = 0.0;
  59509. else
  59510. this._darkness = darkness;
  59511. return this;
  59512. };
  59513. /**
  59514. * Sets the ability to have transparent shadow (boolean).
  59515. * @param transparent True if transparent else False
  59516. * @returns the shadow generator allowing fluent coding
  59517. */
  59518. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59519. this._transparencyShadow = transparent;
  59520. return this;
  59521. };
  59522. /**
  59523. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59524. * @returns The render target texture if present otherwise, null
  59525. */
  59526. ShadowGenerator.prototype.getShadowMap = function () {
  59527. return this._shadowMap;
  59528. };
  59529. /**
  59530. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59531. * @returns The render target texture if the shadow map is present otherwise, null
  59532. */
  59533. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59534. if (this._shadowMap2) {
  59535. return this._shadowMap2;
  59536. }
  59537. return this._shadowMap;
  59538. };
  59539. /**
  59540. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59541. * @param mesh Mesh to add
  59542. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59543. * @returns the Shadow Generator itself
  59544. */
  59545. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59546. if (includeDescendants === void 0) { includeDescendants = true; }
  59547. if (!this._shadowMap) {
  59548. return this;
  59549. }
  59550. if (!this._shadowMap.renderList) {
  59551. this._shadowMap.renderList = [];
  59552. }
  59553. this._shadowMap.renderList.push(mesh);
  59554. if (includeDescendants) {
  59555. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59556. }
  59557. return this;
  59558. var _a;
  59559. };
  59560. /**
  59561. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59562. * @param mesh Mesh to remove
  59563. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59564. * @returns the Shadow Generator itself
  59565. */
  59566. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59567. if (includeDescendants === void 0) { includeDescendants = true; }
  59568. if (!this._shadowMap || !this._shadowMap.renderList) {
  59569. return this;
  59570. }
  59571. var index = this._shadowMap.renderList.indexOf(mesh);
  59572. if (index !== -1) {
  59573. this._shadowMap.renderList.splice(index, 1);
  59574. }
  59575. if (includeDescendants) {
  59576. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59577. var child = _a[_i];
  59578. this.removeShadowCaster(child);
  59579. }
  59580. }
  59581. return this;
  59582. };
  59583. /**
  59584. * Returns the associated light object.
  59585. * @returns the light generating the shadow
  59586. */
  59587. ShadowGenerator.prototype.getLight = function () {
  59588. return this._light;
  59589. };
  59590. ShadowGenerator.prototype._initializeGenerator = function () {
  59591. this._light._markMeshesAsLightDirty();
  59592. this._initializeShadowMap();
  59593. };
  59594. ShadowGenerator.prototype._initializeShadowMap = function () {
  59595. var _this = this;
  59596. // Render target
  59597. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59598. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59599. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59600. this._shadowMap.anisotropicFilteringLevel = 1;
  59601. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59602. this._shadowMap.renderParticles = false;
  59603. this._shadowMap.ignoreCameraViewport = true;
  59604. // Record Face Index before render.
  59605. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59606. _this._currentFaceIndex = faceIndex;
  59607. });
  59608. // Custom render function.
  59609. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59610. // Blur if required afer render.
  59611. this._shadowMap.onAfterUnbindObservable.add(function () {
  59612. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59613. return;
  59614. }
  59615. var shadowMap = _this.getShadowMapForRendering();
  59616. if (shadowMap) {
  59617. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59618. }
  59619. });
  59620. // Clear according to the chosen filter.
  59621. this._shadowMap.onClearObservable.add(function (engine) {
  59622. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59623. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59624. }
  59625. else {
  59626. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59627. }
  59628. });
  59629. };
  59630. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59631. var _this = this;
  59632. var engine = this._scene.getEngine();
  59633. var targetSize = this._mapSize / this.blurScale;
  59634. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59635. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59636. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59637. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59638. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59639. }
  59640. if (this.useKernelBlur) {
  59641. 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);
  59642. this._kernelBlurXPostprocess.width = targetSize;
  59643. this._kernelBlurXPostprocess.height = targetSize;
  59644. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59645. effect.setTexture("textureSampler", _this._shadowMap);
  59646. });
  59647. 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);
  59648. this._kernelBlurXPostprocess.autoClear = false;
  59649. this._kernelBlurYPostprocess.autoClear = false;
  59650. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59651. this._kernelBlurXPostprocess.packedFloat = true;
  59652. this._kernelBlurYPostprocess.packedFloat = true;
  59653. }
  59654. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59655. }
  59656. else {
  59657. 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);
  59658. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59659. effect.setFloat2("screenSize", targetSize, targetSize);
  59660. effect.setTexture("textureSampler", _this._shadowMap);
  59661. });
  59662. this._boxBlurPostprocess.autoClear = false;
  59663. this._blurPostProcesses = [this._boxBlurPostprocess];
  59664. }
  59665. };
  59666. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59667. var index;
  59668. var engine = this._scene.getEngine();
  59669. if (depthOnlySubMeshes.length) {
  59670. engine.setColorWrite(false);
  59671. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59672. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59673. }
  59674. engine.setColorWrite(true);
  59675. }
  59676. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59677. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59678. }
  59679. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59680. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59681. }
  59682. if (this._transparencyShadow) {
  59683. for (index = 0; index < transparentSubMeshes.length; index++) {
  59684. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59685. }
  59686. }
  59687. };
  59688. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59689. var _this = this;
  59690. var mesh = subMesh.getRenderingMesh();
  59691. var scene = this._scene;
  59692. var engine = scene.getEngine();
  59693. var material = subMesh.getMaterial();
  59694. if (!material) {
  59695. return;
  59696. }
  59697. // Culling
  59698. engine.setState(material.backFaceCulling);
  59699. // Managing instances
  59700. var batch = mesh._getInstancesRenderList(subMesh._id);
  59701. if (batch.mustReturn) {
  59702. return;
  59703. }
  59704. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59705. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59706. engine.enableEffect(this._effect);
  59707. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59708. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59709. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59710. this._effect.setVector3("lightPosition", this.getLight().position);
  59711. if (scene.activeCamera) {
  59712. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59713. }
  59714. // Alpha test
  59715. if (material && material.needAlphaTesting()) {
  59716. var alphaTexture = material.getAlphaTestTexture();
  59717. if (alphaTexture) {
  59718. this._effect.setTexture("diffuseSampler", alphaTexture);
  59719. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59720. }
  59721. }
  59722. // Bones
  59723. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59724. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59725. }
  59726. if (this.forceBackFacesOnly) {
  59727. engine.setState(true, 0, false, true);
  59728. }
  59729. // Draw
  59730. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59731. if (this.forceBackFacesOnly) {
  59732. engine.setState(true, 0, false, false);
  59733. }
  59734. }
  59735. else {
  59736. // Need to reset refresh rate of the shadowMap
  59737. if (this._shadowMap) {
  59738. this._shadowMap.resetRefreshCounter();
  59739. }
  59740. }
  59741. };
  59742. ShadowGenerator.prototype._applyFilterValues = function () {
  59743. if (!this._shadowMap) {
  59744. return;
  59745. }
  59746. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59747. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59748. }
  59749. else {
  59750. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59751. }
  59752. };
  59753. /**
  59754. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59755. * @param onCompiled Callback triggered at the and of the effects compilation
  59756. * @param options Sets of optional options forcing the compilation with different modes
  59757. */
  59758. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59759. var _this = this;
  59760. var localOptions = __assign({ useInstances: false }, options);
  59761. var shadowMap = this.getShadowMap();
  59762. if (!shadowMap) {
  59763. if (onCompiled) {
  59764. onCompiled(this);
  59765. }
  59766. return;
  59767. }
  59768. var renderList = shadowMap.renderList;
  59769. if (!renderList) {
  59770. if (onCompiled) {
  59771. onCompiled(this);
  59772. }
  59773. return;
  59774. }
  59775. var subMeshes = new Array();
  59776. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59777. var mesh = renderList_1[_i];
  59778. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59779. }
  59780. if (subMeshes.length === 0) {
  59781. if (onCompiled) {
  59782. onCompiled(this);
  59783. }
  59784. return;
  59785. }
  59786. var currentIndex = 0;
  59787. var checkReady = function () {
  59788. if (!_this._scene || !_this._scene.getEngine()) {
  59789. return;
  59790. }
  59791. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59792. currentIndex++;
  59793. if (currentIndex >= subMeshes.length) {
  59794. if (onCompiled) {
  59795. onCompiled(_this);
  59796. }
  59797. return;
  59798. }
  59799. }
  59800. setTimeout(checkReady, 16);
  59801. };
  59802. checkReady();
  59803. };
  59804. /**
  59805. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59806. * @param options Sets of optional options forcing the compilation with different modes
  59807. * @returns A promise that resolves when the compilation completes
  59808. */
  59809. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59810. var _this = this;
  59811. return new Promise(function (resolve) {
  59812. _this.forceCompilation(function () {
  59813. resolve();
  59814. }, options);
  59815. });
  59816. };
  59817. /**
  59818. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59819. * @param subMesh The submesh we want to render in the shadow map
  59820. * @param useInstances Defines wether will draw in the map using instances
  59821. * @returns true if ready otherwise, false
  59822. */
  59823. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59824. var defines = [];
  59825. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59826. defines.push("#define FLOAT");
  59827. }
  59828. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59829. defines.push("#define ESM");
  59830. }
  59831. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59832. var mesh = subMesh.getMesh();
  59833. var material = subMesh.getMaterial();
  59834. // Alpha test
  59835. if (material && material.needAlphaTesting()) {
  59836. var alphaTexture = material.getAlphaTestTexture();
  59837. if (alphaTexture) {
  59838. defines.push("#define ALPHATEST");
  59839. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59840. attribs.push(BABYLON.VertexBuffer.UVKind);
  59841. defines.push("#define UV1");
  59842. }
  59843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59844. if (alphaTexture.coordinatesIndex === 1) {
  59845. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59846. defines.push("#define UV2");
  59847. }
  59848. }
  59849. }
  59850. }
  59851. // Bones
  59852. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59855. if (mesh.numBoneInfluencers > 4) {
  59856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59858. }
  59859. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59860. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59861. }
  59862. else {
  59863. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59864. }
  59865. // Instances
  59866. if (useInstances) {
  59867. defines.push("#define INSTANCES");
  59868. attribs.push("world0");
  59869. attribs.push("world1");
  59870. attribs.push("world2");
  59871. attribs.push("world3");
  59872. }
  59873. // Get correct effect
  59874. var join = defines.join("\n");
  59875. if (this._cachedDefines !== join) {
  59876. this._cachedDefines = join;
  59877. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59878. }
  59879. if (!this._effect.isReady()) {
  59880. return false;
  59881. }
  59882. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59883. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59884. this._initializeBlurRTTAndPostProcesses();
  59885. }
  59886. }
  59887. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59888. return false;
  59889. }
  59890. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59891. return false;
  59892. }
  59893. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59894. return false;
  59895. }
  59896. return true;
  59897. };
  59898. /**
  59899. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59900. * @param defines Defines of the material we want to update
  59901. * @param lightIndex Index of the light in the enabled light list of the material
  59902. */
  59903. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59904. var scene = this._scene;
  59905. var light = this._light;
  59906. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59907. return;
  59908. }
  59909. defines["SHADOW" + lightIndex] = true;
  59910. if (this.usePoissonSampling) {
  59911. defines["SHADOWPCF" + lightIndex] = true;
  59912. }
  59913. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59914. defines["SHADOWESM" + lightIndex] = true;
  59915. }
  59916. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59917. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59918. }
  59919. if (light.needCube()) {
  59920. defines["SHADOWCUBE" + lightIndex] = true;
  59921. }
  59922. };
  59923. /**
  59924. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59925. * defined in the generator but impacting the effect).
  59926. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59927. * @param effect The effect we are binfing the information for
  59928. */
  59929. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59930. var light = this._light;
  59931. var scene = this._scene;
  59932. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59933. return;
  59934. }
  59935. var camera = scene.activeCamera;
  59936. if (!camera) {
  59937. return;
  59938. }
  59939. var shadowMap = this.getShadowMap();
  59940. if (!shadowMap) {
  59941. return;
  59942. }
  59943. if (!light.needCube()) {
  59944. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59945. }
  59946. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59947. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59948. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59949. };
  59950. /**
  59951. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59952. * (eq to shadow prjection matrix * light transform matrix)
  59953. * @returns The transform matrix used to create the shadow map
  59954. */
  59955. ShadowGenerator.prototype.getTransformMatrix = function () {
  59956. var scene = this._scene;
  59957. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59958. return this._transformMatrix;
  59959. }
  59960. this._currentRenderID = scene.getRenderId();
  59961. this._currentFaceIndexCache = this._currentFaceIndex;
  59962. var lightPosition = this._light.position;
  59963. if (this._light.computeTransformedInformation()) {
  59964. lightPosition = this._light.transformedPosition;
  59965. }
  59966. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59967. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59968. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59969. }
  59970. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59971. this._cachedPosition = lightPosition.clone();
  59972. this._cachedDirection = this._lightDirection.clone();
  59973. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59974. var shadowMap = this.getShadowMap();
  59975. if (shadowMap) {
  59976. var renderList = shadowMap.renderList;
  59977. if (renderList) {
  59978. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59979. }
  59980. }
  59981. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59982. }
  59983. return this._transformMatrix;
  59984. };
  59985. /**
  59986. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59987. * Cube and 2D textures for instance.
  59988. */
  59989. ShadowGenerator.prototype.recreateShadowMap = function () {
  59990. var shadowMap = this._shadowMap;
  59991. if (!shadowMap) {
  59992. return;
  59993. }
  59994. // Track render list.
  59995. var renderList = shadowMap.renderList;
  59996. // Clean up existing data.
  59997. this._disposeRTTandPostProcesses();
  59998. // Reinitializes.
  59999. this._initializeGenerator();
  60000. // Reaffect the filter to ensure a correct fallback if necessary.
  60001. this.filter = this.filter;
  60002. // Reaffect the filter.
  60003. this._applyFilterValues();
  60004. // Reaffect Render List.
  60005. this._shadowMap.renderList = renderList;
  60006. };
  60007. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60008. if (this._shadowMap2) {
  60009. this._shadowMap2.dispose();
  60010. this._shadowMap2 = null;
  60011. }
  60012. if (this._boxBlurPostprocess) {
  60013. this._boxBlurPostprocess.dispose();
  60014. this._boxBlurPostprocess = null;
  60015. }
  60016. if (this._kernelBlurXPostprocess) {
  60017. this._kernelBlurXPostprocess.dispose();
  60018. this._kernelBlurXPostprocess = null;
  60019. }
  60020. if (this._kernelBlurYPostprocess) {
  60021. this._kernelBlurYPostprocess.dispose();
  60022. this._kernelBlurYPostprocess = null;
  60023. }
  60024. this._blurPostProcesses = [];
  60025. };
  60026. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60027. if (this._shadowMap) {
  60028. this._shadowMap.dispose();
  60029. this._shadowMap = null;
  60030. }
  60031. this._disposeBlurPostProcesses();
  60032. };
  60033. /**
  60034. * Disposes the ShadowGenerator.
  60035. * Returns nothing.
  60036. */
  60037. ShadowGenerator.prototype.dispose = function () {
  60038. this._disposeRTTandPostProcesses();
  60039. if (this._light) {
  60040. this._light._shadowGenerator = null;
  60041. this._light._markMeshesAsLightDirty();
  60042. }
  60043. };
  60044. /**
  60045. * Serializes the shadow generator setup to a json object.
  60046. * @returns The serialized JSON object
  60047. */
  60048. ShadowGenerator.prototype.serialize = function () {
  60049. var serializationObject = {};
  60050. var shadowMap = this.getShadowMap();
  60051. if (!shadowMap) {
  60052. return serializationObject;
  60053. }
  60054. serializationObject.lightId = this._light.id;
  60055. serializationObject.mapSize = shadowMap.getRenderSize();
  60056. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60057. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60058. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60059. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60060. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60061. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60062. serializationObject.depthScale = this.depthScale;
  60063. serializationObject.darkness = this.getDarkness();
  60064. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60065. serializationObject.blurKernel = this.blurKernel;
  60066. serializationObject.blurScale = this.blurScale;
  60067. serializationObject.useKernelBlur = this.useKernelBlur;
  60068. serializationObject.transparencyShadow = this._transparencyShadow;
  60069. serializationObject.renderList = [];
  60070. if (shadowMap.renderList) {
  60071. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60072. var mesh = shadowMap.renderList[meshIndex];
  60073. serializationObject.renderList.push(mesh.id);
  60074. }
  60075. }
  60076. return serializationObject;
  60077. };
  60078. /**
  60079. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60080. * @param parsedShadowGenerator The JSON object to parse
  60081. * @param scene The scene to create the shadow map for
  60082. * @returns The parsed shadow generator
  60083. */
  60084. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60085. //casting to point light, as light is missing the position attr and typescript complains.
  60086. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60087. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60088. var shadowMap = shadowGenerator.getShadowMap();
  60089. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60090. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60091. meshes.forEach(function (mesh) {
  60092. if (!shadowMap) {
  60093. return;
  60094. }
  60095. if (!shadowMap.renderList) {
  60096. shadowMap.renderList = [];
  60097. }
  60098. shadowMap.renderList.push(mesh);
  60099. });
  60100. }
  60101. if (parsedShadowGenerator.usePoissonSampling) {
  60102. shadowGenerator.usePoissonSampling = true;
  60103. }
  60104. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60105. shadowGenerator.useExponentialShadowMap = true;
  60106. }
  60107. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60108. shadowGenerator.useBlurExponentialShadowMap = true;
  60109. }
  60110. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60111. shadowGenerator.useCloseExponentialShadowMap = true;
  60112. }
  60113. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60114. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60115. }
  60116. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60117. shadowGenerator.useExponentialShadowMap = true;
  60118. }
  60119. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60120. shadowGenerator.useBlurExponentialShadowMap = true;
  60121. }
  60122. if (parsedShadowGenerator.depthScale) {
  60123. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60124. }
  60125. if (parsedShadowGenerator.blurScale) {
  60126. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60127. }
  60128. if (parsedShadowGenerator.blurBoxOffset) {
  60129. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60130. }
  60131. if (parsedShadowGenerator.useKernelBlur) {
  60132. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60133. }
  60134. if (parsedShadowGenerator.blurKernel) {
  60135. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60136. }
  60137. if (parsedShadowGenerator.bias !== undefined) {
  60138. shadowGenerator.bias = parsedShadowGenerator.bias;
  60139. }
  60140. if (parsedShadowGenerator.darkness) {
  60141. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60142. }
  60143. if (parsedShadowGenerator.transparencyShadow) {
  60144. shadowGenerator.setTransparencyShadow(true);
  60145. }
  60146. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60147. return shadowGenerator;
  60148. };
  60149. ShadowGenerator._FILTER_NONE = 0;
  60150. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60151. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60152. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60153. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60154. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60155. return ShadowGenerator;
  60156. }());
  60157. BABYLON.ShadowGenerator = ShadowGenerator;
  60158. })(BABYLON || (BABYLON = {}));
  60159. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60160. var BABYLON;
  60161. (function (BABYLON) {
  60162. var DefaultLoadingScreen = /** @class */ (function () {
  60163. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60164. if (_loadingText === void 0) { _loadingText = ""; }
  60165. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60166. var _this = this;
  60167. this._renderingCanvas = _renderingCanvas;
  60168. this._loadingText = _loadingText;
  60169. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60170. // Resize
  60171. this._resizeLoadingUI = function () {
  60172. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60173. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60174. if (!_this._loadingDiv) {
  60175. return;
  60176. }
  60177. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60178. _this._loadingDiv.style.left = canvasRect.left + "px";
  60179. _this._loadingDiv.style.top = canvasRect.top + "px";
  60180. _this._loadingDiv.style.width = canvasRect.width + "px";
  60181. _this._loadingDiv.style.height = canvasRect.height + "px";
  60182. };
  60183. }
  60184. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60185. if (this._loadingDiv) {
  60186. // Do not add a loading screen if there is already one
  60187. return;
  60188. }
  60189. this._loadingDiv = document.createElement("div");
  60190. this._loadingDiv.id = "babylonjsLoadingDiv";
  60191. this._loadingDiv.style.opacity = "0";
  60192. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60193. this._loadingDiv.style.pointerEvents = "none";
  60194. // Loading text
  60195. this._loadingTextDiv = document.createElement("div");
  60196. this._loadingTextDiv.style.position = "absolute";
  60197. this._loadingTextDiv.style.left = "0";
  60198. this._loadingTextDiv.style.top = "50%";
  60199. this._loadingTextDiv.style.marginTop = "80px";
  60200. this._loadingTextDiv.style.width = "100%";
  60201. this._loadingTextDiv.style.height = "20px";
  60202. this._loadingTextDiv.style.fontFamily = "Arial";
  60203. this._loadingTextDiv.style.fontSize = "14px";
  60204. this._loadingTextDiv.style.color = "white";
  60205. this._loadingTextDiv.style.textAlign = "center";
  60206. this._loadingTextDiv.innerHTML = "Loading";
  60207. this._loadingDiv.appendChild(this._loadingTextDiv);
  60208. //set the predefined text
  60209. this._loadingTextDiv.innerHTML = this._loadingText;
  60210. // Generating keyframes
  60211. var style = document.createElement('style');
  60212. style.type = 'text/css';
  60213. 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 }";
  60214. style.innerHTML = keyFrames;
  60215. document.getElementsByTagName('head')[0].appendChild(style);
  60216. // Loading img
  60217. var imgBack = new Image();
  60218. 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";
  60219. imgBack.style.position = "absolute";
  60220. imgBack.style.left = "50%";
  60221. imgBack.style.top = "50%";
  60222. imgBack.style.marginLeft = "-60px";
  60223. imgBack.style.marginTop = "-60px";
  60224. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60225. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60226. imgBack.style.transformOrigin = "50% 50%";
  60227. imgBack.style.webkitTransformOrigin = "50% 50%";
  60228. this._loadingDiv.appendChild(imgBack);
  60229. this._resizeLoadingUI();
  60230. window.addEventListener("resize", this._resizeLoadingUI);
  60231. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60232. document.body.appendChild(this._loadingDiv);
  60233. this._loadingDiv.style.opacity = "1";
  60234. };
  60235. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60236. var _this = this;
  60237. if (!this._loadingDiv) {
  60238. return;
  60239. }
  60240. var onTransitionEnd = function () {
  60241. if (!_this._loadingDiv) {
  60242. return;
  60243. }
  60244. document.body.removeChild(_this._loadingDiv);
  60245. window.removeEventListener("resize", _this._resizeLoadingUI);
  60246. _this._loadingDiv = null;
  60247. };
  60248. this._loadingDiv.style.opacity = "0";
  60249. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60250. };
  60251. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60252. set: function (text) {
  60253. this._loadingText = text;
  60254. if (this._loadingTextDiv) {
  60255. this._loadingTextDiv.innerHTML = this._loadingText;
  60256. }
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60262. get: function () {
  60263. return this._loadingDivBackgroundColor;
  60264. },
  60265. set: function (color) {
  60266. this._loadingDivBackgroundColor = color;
  60267. if (!this._loadingDiv) {
  60268. return;
  60269. }
  60270. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60271. },
  60272. enumerable: true,
  60273. configurable: true
  60274. });
  60275. return DefaultLoadingScreen;
  60276. }());
  60277. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60278. })(BABYLON || (BABYLON = {}));
  60279. //# sourceMappingURL=babylon.loadingScreen.js.map
  60280. var BABYLON;
  60281. (function (BABYLON) {
  60282. var SceneLoaderProgressEvent = /** @class */ (function () {
  60283. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60284. this.lengthComputable = lengthComputable;
  60285. this.loaded = loaded;
  60286. this.total = total;
  60287. }
  60288. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60289. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60290. };
  60291. return SceneLoaderProgressEvent;
  60292. }());
  60293. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60294. var SceneLoader = /** @class */ (function () {
  60295. function SceneLoader() {
  60296. }
  60297. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60298. get: function () {
  60299. return 0;
  60300. },
  60301. enumerable: true,
  60302. configurable: true
  60303. });
  60304. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60305. get: function () {
  60306. return 1;
  60307. },
  60308. enumerable: true,
  60309. configurable: true
  60310. });
  60311. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60312. get: function () {
  60313. return 2;
  60314. },
  60315. enumerable: true,
  60316. configurable: true
  60317. });
  60318. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60319. get: function () {
  60320. return 3;
  60321. },
  60322. enumerable: true,
  60323. configurable: true
  60324. });
  60325. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60326. get: function () {
  60327. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60328. },
  60329. set: function (value) {
  60330. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60331. },
  60332. enumerable: true,
  60333. configurable: true
  60334. });
  60335. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60336. get: function () {
  60337. return SceneLoader._ShowLoadingScreen;
  60338. },
  60339. set: function (value) {
  60340. SceneLoader._ShowLoadingScreen = value;
  60341. },
  60342. enumerable: true,
  60343. configurable: true
  60344. });
  60345. Object.defineProperty(SceneLoader, "loggingLevel", {
  60346. get: function () {
  60347. return SceneLoader._loggingLevel;
  60348. },
  60349. set: function (value) {
  60350. SceneLoader._loggingLevel = value;
  60351. },
  60352. enumerable: true,
  60353. configurable: true
  60354. });
  60355. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60356. get: function () {
  60357. return SceneLoader._CleanBoneMatrixWeights;
  60358. },
  60359. set: function (value) {
  60360. SceneLoader._CleanBoneMatrixWeights = value;
  60361. },
  60362. enumerable: true,
  60363. configurable: true
  60364. });
  60365. SceneLoader._getDefaultPlugin = function () {
  60366. return SceneLoader._registeredPlugins[".babylon"];
  60367. };
  60368. SceneLoader._getPluginForExtension = function (extension) {
  60369. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60370. if (registeredPlugin) {
  60371. return registeredPlugin;
  60372. }
  60373. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60374. return SceneLoader._getDefaultPlugin();
  60375. };
  60376. SceneLoader._getPluginForDirectLoad = function (data) {
  60377. for (var extension in SceneLoader._registeredPlugins) {
  60378. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60379. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60380. return SceneLoader._registeredPlugins[extension];
  60381. }
  60382. }
  60383. return SceneLoader._getDefaultPlugin();
  60384. };
  60385. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60386. if (sceneFilename.name) {
  60387. sceneFilename = sceneFilename.name;
  60388. }
  60389. var queryStringPosition = sceneFilename.indexOf("?");
  60390. if (queryStringPosition !== -1) {
  60391. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60392. }
  60393. var dotPosition = sceneFilename.lastIndexOf(".");
  60394. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60395. return SceneLoader._getPluginForExtension(extension);
  60396. };
  60397. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60398. SceneLoader._getDirectLoad = function (sceneFilename) {
  60399. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60400. return sceneFilename.substr(5);
  60401. }
  60402. return null;
  60403. };
  60404. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60405. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60406. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60407. var plugin;
  60408. if (registeredPlugin.plugin.createPlugin) {
  60409. plugin = registeredPlugin.plugin.createPlugin();
  60410. }
  60411. else {
  60412. plugin = registeredPlugin.plugin;
  60413. }
  60414. var useArrayBuffer = registeredPlugin.isBinary;
  60415. var database;
  60416. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60417. var dataCallback = function (data, responseURL) {
  60418. if (scene.isDisposed) {
  60419. onError("Scene has been disposed");
  60420. return;
  60421. }
  60422. scene.database = database;
  60423. onSuccess(plugin, data, responseURL);
  60424. };
  60425. var request = null;
  60426. var pluginDisposed = false;
  60427. var onDisposeObservable = plugin.onDisposeObservable;
  60428. if (onDisposeObservable) {
  60429. onDisposeObservable.add(function () {
  60430. pluginDisposed = true;
  60431. if (request) {
  60432. request.abort();
  60433. request = null;
  60434. }
  60435. onDispose();
  60436. });
  60437. }
  60438. var manifestChecked = function () {
  60439. if (pluginDisposed) {
  60440. return;
  60441. }
  60442. var url = rootUrl + sceneFilename;
  60443. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60444. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60445. } : undefined, database, useArrayBuffer, function (request, exception) {
  60446. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60447. });
  60448. };
  60449. if (directLoad) {
  60450. dataCallback(directLoad);
  60451. return plugin;
  60452. }
  60453. if (rootUrl.indexOf("file:") === -1) {
  60454. if (scene.getEngine().enableOfflineSupport) {
  60455. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60456. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60457. }
  60458. else {
  60459. manifestChecked();
  60460. }
  60461. }
  60462. else {
  60463. var fileOrString = sceneFilename;
  60464. if (fileOrString.name) {
  60465. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60466. }
  60467. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60468. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60469. }
  60470. else {
  60471. onError("Unable to find file named " + sceneFilename);
  60472. }
  60473. }
  60474. return plugin;
  60475. };
  60476. // Public functions
  60477. SceneLoader.GetPluginForExtension = function (extension) {
  60478. return SceneLoader._getPluginForExtension(extension).plugin;
  60479. };
  60480. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60481. return !!SceneLoader._registeredPlugins[extension];
  60482. };
  60483. SceneLoader.RegisterPlugin = function (plugin) {
  60484. if (typeof plugin.extensions === "string") {
  60485. var extension = plugin.extensions;
  60486. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60487. plugin: plugin,
  60488. isBinary: false
  60489. };
  60490. }
  60491. else {
  60492. var extensions = plugin.extensions;
  60493. Object.keys(extensions).forEach(function (extension) {
  60494. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60495. plugin: plugin,
  60496. isBinary: extensions[extension].isBinary
  60497. };
  60498. });
  60499. }
  60500. };
  60501. /**
  60502. * Import meshes into a scene
  60503. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60504. * @param rootUrl a string that defines the root url for scene and resources
  60505. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60506. * @param scene the instance of BABYLON.Scene to append to
  60507. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60508. * @param onProgress a callback with a progress event for each file being loaded
  60509. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60510. * @param pluginExtension the extension used to determine the plugin
  60511. * @returns The loaded plugin
  60512. */
  60513. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60514. if (onSuccess === void 0) { onSuccess = null; }
  60515. if (onProgress === void 0) { onProgress = null; }
  60516. if (onError === void 0) { onError = null; }
  60517. if (pluginExtension === void 0) { pluginExtension = null; }
  60518. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60519. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60520. return null;
  60521. }
  60522. var loadingToken = {};
  60523. scene._addPendingData(loadingToken);
  60524. var disposeHandler = function () {
  60525. scene._removePendingData(loadingToken);
  60526. };
  60527. var errorHandler = function (message, exception) {
  60528. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60529. if (onError) {
  60530. onError(scene, errorMessage, exception);
  60531. }
  60532. else {
  60533. BABYLON.Tools.Error(errorMessage);
  60534. // should the exception be thrown?
  60535. }
  60536. disposeHandler();
  60537. };
  60538. var progressHandler = onProgress ? function (event) {
  60539. try {
  60540. onProgress(event);
  60541. }
  60542. catch (e) {
  60543. errorHandler("Error in onProgress callback", e);
  60544. }
  60545. } : undefined;
  60546. var successHandler = function (meshes, particleSystems, skeletons) {
  60547. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60548. if (onSuccess) {
  60549. try {
  60550. onSuccess(meshes, particleSystems, skeletons);
  60551. }
  60552. catch (e) {
  60553. errorHandler("Error in onSuccess callback", e);
  60554. }
  60555. }
  60556. scene._removePendingData(loadingToken);
  60557. };
  60558. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60559. if (plugin.rewriteRootURL) {
  60560. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60561. }
  60562. if (sceneFilename === "") {
  60563. if (sceneFilename === "") {
  60564. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60565. }
  60566. }
  60567. if (plugin.importMesh) {
  60568. var syncedPlugin = plugin;
  60569. var meshes = new Array();
  60570. var particleSystems = new Array();
  60571. var skeletons = new Array();
  60572. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60573. return;
  60574. }
  60575. scene.loadingPluginName = plugin.name;
  60576. successHandler(meshes, particleSystems, skeletons);
  60577. }
  60578. else {
  60579. var asyncedPlugin = plugin;
  60580. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60581. scene.loadingPluginName = plugin.name;
  60582. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60583. }).catch(function (error) {
  60584. errorHandler(error.message, error);
  60585. });
  60586. }
  60587. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60588. };
  60589. /**
  60590. * Import meshes into a scene
  60591. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60592. * @param rootUrl a string that defines the root url for scene and resources
  60593. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60594. * @param scene the instance of BABYLON.Scene to append to
  60595. * @param onProgress a callback with a progress event for each file being loaded
  60596. * @param pluginExtension the extension used to determine the plugin
  60597. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60598. */
  60599. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60600. if (onProgress === void 0) { onProgress = null; }
  60601. if (pluginExtension === void 0) { pluginExtension = null; }
  60602. return new Promise(function (resolve, reject) {
  60603. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60604. resolve({
  60605. meshes: meshes,
  60606. particleSystems: particleSystems,
  60607. skeletons: skeletons
  60608. });
  60609. }, onProgress, function (scene, message, exception) {
  60610. reject(exception || new Error(message));
  60611. });
  60612. });
  60613. };
  60614. /**
  60615. * Load a scene
  60616. * @param rootUrl a string that defines the root url for scene and resources
  60617. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60618. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60619. * @param onSuccess a callback with the scene when import succeeds
  60620. * @param onProgress a callback with a progress event for each file being loaded
  60621. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60622. * @param pluginExtension the extension used to determine the plugin
  60623. * @returns The loaded plugin
  60624. */
  60625. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60626. if (onSuccess === void 0) { onSuccess = null; }
  60627. if (onProgress === void 0) { onProgress = null; }
  60628. if (onError === void 0) { onError = null; }
  60629. if (pluginExtension === void 0) { pluginExtension = null; }
  60630. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60631. };
  60632. /**
  60633. * Load a scene
  60634. * @param rootUrl a string that defines the root url for scene and resources
  60635. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60636. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60637. * @param onProgress a callback with a progress event for each file being loaded
  60638. * @param pluginExtension the extension used to determine the plugin
  60639. * @returns The loaded scene
  60640. */
  60641. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60642. if (onProgress === void 0) { onProgress = null; }
  60643. if (pluginExtension === void 0) { pluginExtension = null; }
  60644. return new Promise(function (resolve, reject) {
  60645. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60646. resolve(scene);
  60647. }, onProgress, function (scene, message, exception) {
  60648. reject(exception || new Error(message));
  60649. }, pluginExtension);
  60650. });
  60651. };
  60652. /**
  60653. * Append a scene
  60654. * @param rootUrl a string that defines the root url for scene and resources
  60655. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60656. * @param scene is the instance of BABYLON.Scene to append to
  60657. * @param onSuccess a callback with the scene when import succeeds
  60658. * @param onProgress a callback with a progress event for each file being loaded
  60659. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60660. * @param pluginExtension the extension used to determine the plugin
  60661. * @returns The loaded plugin
  60662. */
  60663. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60664. if (onSuccess === void 0) { onSuccess = null; }
  60665. if (onProgress === void 0) { onProgress = null; }
  60666. if (onError === void 0) { onError = null; }
  60667. if (pluginExtension === void 0) { pluginExtension = null; }
  60668. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60669. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60670. return null;
  60671. }
  60672. if (SceneLoader.ShowLoadingScreen) {
  60673. scene.getEngine().displayLoadingUI();
  60674. }
  60675. var loadingToken = {};
  60676. scene._addPendingData(loadingToken);
  60677. var disposeHandler = function () {
  60678. scene._removePendingData(loadingToken);
  60679. scene.getEngine().hideLoadingUI();
  60680. };
  60681. var errorHandler = function (message, exception) {
  60682. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60683. if (onError) {
  60684. onError(scene, errorMessage, exception);
  60685. }
  60686. else {
  60687. BABYLON.Tools.Error(errorMessage);
  60688. // should the exception be thrown?
  60689. }
  60690. disposeHandler();
  60691. };
  60692. var progressHandler = onProgress ? function (event) {
  60693. try {
  60694. onProgress(event);
  60695. }
  60696. catch (e) {
  60697. errorHandler("Error in onProgress callback", e);
  60698. }
  60699. } : undefined;
  60700. var successHandler = function () {
  60701. if (onSuccess) {
  60702. try {
  60703. onSuccess(scene);
  60704. }
  60705. catch (e) {
  60706. errorHandler("Error in onSuccess callback", e);
  60707. }
  60708. }
  60709. scene._removePendingData(loadingToken);
  60710. };
  60711. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60712. if (sceneFilename === "") {
  60713. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60714. }
  60715. if (plugin.load) {
  60716. var syncedPlugin = plugin;
  60717. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60718. return;
  60719. }
  60720. scene.loadingPluginName = plugin.name;
  60721. successHandler();
  60722. }
  60723. else {
  60724. var asyncedPlugin = plugin;
  60725. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60726. scene.loadingPluginName = plugin.name;
  60727. successHandler();
  60728. }).catch(function (error) {
  60729. errorHandler(error.message, error);
  60730. });
  60731. }
  60732. if (SceneLoader.ShowLoadingScreen) {
  60733. scene.executeWhenReady(function () {
  60734. scene.getEngine().hideLoadingUI();
  60735. });
  60736. }
  60737. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60738. };
  60739. /**
  60740. * Append a scene
  60741. * @param rootUrl a string that defines the root url for scene and resources
  60742. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60743. * @param scene is the instance of BABYLON.Scene to append to
  60744. * @param onProgress a callback with a progress event for each file being loaded
  60745. * @param pluginExtension the extension used to determine the plugin
  60746. * @returns The given scene
  60747. */
  60748. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60749. if (onProgress === void 0) { onProgress = null; }
  60750. if (pluginExtension === void 0) { pluginExtension = null; }
  60751. return new Promise(function (resolve, reject) {
  60752. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60753. resolve(scene);
  60754. }, onProgress, function (scene, message, exception) {
  60755. reject(exception || new Error(message));
  60756. }, pluginExtension);
  60757. });
  60758. };
  60759. /**
  60760. * Load a scene into an asset container
  60761. * @param rootUrl a string that defines the root url for scene and resources
  60762. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60763. * @param scene is the instance of BABYLON.Scene to append to
  60764. * @param onSuccess a callback with the scene when import succeeds
  60765. * @param onProgress a callback with a progress event for each file being loaded
  60766. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60767. * @param pluginExtension the extension used to determine the plugin
  60768. * @returns The loaded plugin
  60769. */
  60770. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60771. if (onSuccess === void 0) { onSuccess = null; }
  60772. if (onProgress === void 0) { onProgress = null; }
  60773. if (onError === void 0) { onError = null; }
  60774. if (pluginExtension === void 0) { pluginExtension = null; }
  60775. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60776. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60777. return null;
  60778. }
  60779. var loadingToken = {};
  60780. scene._addPendingData(loadingToken);
  60781. var disposeHandler = function () {
  60782. scene._removePendingData(loadingToken);
  60783. };
  60784. var errorHandler = function (message, exception) {
  60785. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60786. if (onError) {
  60787. onError(scene, errorMessage, exception);
  60788. }
  60789. else {
  60790. BABYLON.Tools.Error(errorMessage);
  60791. // should the exception be thrown?
  60792. }
  60793. disposeHandler();
  60794. };
  60795. var progressHandler = onProgress ? function (event) {
  60796. try {
  60797. onProgress(event);
  60798. }
  60799. catch (e) {
  60800. errorHandler("Error in onProgress callback", e);
  60801. }
  60802. } : undefined;
  60803. var successHandler = function (assets) {
  60804. if (onSuccess) {
  60805. try {
  60806. onSuccess(assets);
  60807. }
  60808. catch (e) {
  60809. errorHandler("Error in onSuccess callback", e);
  60810. }
  60811. }
  60812. scene._removePendingData(loadingToken);
  60813. };
  60814. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60815. if (plugin.loadAssetContainer) {
  60816. var syncedPlugin = plugin;
  60817. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60818. if (!assetContainer) {
  60819. return;
  60820. }
  60821. scene.loadingPluginName = plugin.name;
  60822. successHandler(assetContainer);
  60823. }
  60824. else if (plugin.loadAssetContainerAsync) {
  60825. var asyncedPlugin = plugin;
  60826. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60827. scene.loadingPluginName = plugin.name;
  60828. successHandler(assetContainer);
  60829. }).catch(function (error) {
  60830. errorHandler(error.message, error);
  60831. });
  60832. }
  60833. else {
  60834. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60835. }
  60836. if (SceneLoader.ShowLoadingScreen) {
  60837. scene.executeWhenReady(function () {
  60838. scene.getEngine().hideLoadingUI();
  60839. });
  60840. }
  60841. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60842. };
  60843. /**
  60844. * Load a scene into an asset container
  60845. * @param rootUrl a string that defines the root url for scene and resources
  60846. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60847. * @param scene is the instance of BABYLON.Scene to append to
  60848. * @param onProgress a callback with a progress event for each file being loaded
  60849. * @param pluginExtension the extension used to determine the plugin
  60850. * @returns The loaded asset container
  60851. */
  60852. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60853. if (onProgress === void 0) { onProgress = null; }
  60854. if (pluginExtension === void 0) { pluginExtension = null; }
  60855. return new Promise(function (resolve, reject) {
  60856. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60857. resolve(assetContainer);
  60858. }, onProgress, function (scene, message, exception) {
  60859. reject(exception || new Error(message));
  60860. }, pluginExtension);
  60861. });
  60862. };
  60863. // Flags
  60864. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60865. SceneLoader._ShowLoadingScreen = true;
  60866. SceneLoader._CleanBoneMatrixWeights = false;
  60867. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60868. // Members
  60869. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60870. SceneLoader._registeredPlugins = {};
  60871. return SceneLoader;
  60872. }());
  60873. BABYLON.SceneLoader = SceneLoader;
  60874. ;
  60875. })(BABYLON || (BABYLON = {}));
  60876. //# sourceMappingURL=babylon.sceneLoader.js.map
  60877. var BABYLON;
  60878. (function (BABYLON) {
  60879. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60880. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60881. var parsedMaterial = parsedData.materials[index];
  60882. if (parsedMaterial.id === id) {
  60883. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60884. }
  60885. }
  60886. return null;
  60887. };
  60888. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60889. for (var i in names) {
  60890. if (mesh.name === names[i]) {
  60891. hierarchyIds.push(mesh.id);
  60892. return true;
  60893. }
  60894. }
  60895. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60896. hierarchyIds.push(mesh.id);
  60897. return true;
  60898. }
  60899. return false;
  60900. };
  60901. var logOperation = function (operation, producer) {
  60902. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60903. };
  60904. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60905. if (addToScene === void 0) { addToScene = false; }
  60906. var container = new BABYLON.AssetContainer(scene);
  60907. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60908. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60909. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60910. // and avoid problems with multiple concurrent .babylon loads.
  60911. var log = "importScene has failed JSON parse";
  60912. try {
  60913. var parsedData = JSON.parse(data);
  60914. log = "";
  60915. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60916. var index;
  60917. var cache;
  60918. // Lights
  60919. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60920. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60921. var parsedLight = parsedData.lights[index];
  60922. var light = BABYLON.Light.Parse(parsedLight, scene);
  60923. if (light) {
  60924. container.lights.push(light);
  60925. log += (index === 0 ? "\n\tLights:" : "");
  60926. log += "\n\t\t" + light.toString(fullDetails);
  60927. }
  60928. }
  60929. }
  60930. // Animations
  60931. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60932. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60933. var parsedAnimation = parsedData.animations[index];
  60934. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60935. scene.animations.push(animation);
  60936. container.animations.push(animation);
  60937. log += (index === 0 ? "\n\tAnimations:" : "");
  60938. log += "\n\t\t" + animation.toString(fullDetails);
  60939. }
  60940. }
  60941. // Materials
  60942. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60943. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60944. var parsedMaterial = parsedData.materials[index];
  60945. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60946. container.materials.push(mat);
  60947. log += (index === 0 ? "\n\tMaterials:" : "");
  60948. log += "\n\t\t" + mat.toString(fullDetails);
  60949. }
  60950. }
  60951. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60952. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60953. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60954. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60955. container.multiMaterials.push(mmat);
  60956. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60957. log += "\n\t\t" + mmat.toString(fullDetails);
  60958. }
  60959. }
  60960. // Morph targets
  60961. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60962. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60963. var managerData = _a[_i];
  60964. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60965. }
  60966. }
  60967. // Skeletons
  60968. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60969. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60970. var parsedSkeleton = parsedData.skeletons[index];
  60971. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60972. container.skeletons.push(skeleton);
  60973. log += (index === 0 ? "\n\tSkeletons:" : "");
  60974. log += "\n\t\t" + skeleton.toString(fullDetails);
  60975. }
  60976. }
  60977. // Geometries
  60978. var geometries = parsedData.geometries;
  60979. if (geometries !== undefined && geometries !== null) {
  60980. var addedGeometry = new Array();
  60981. // Boxes
  60982. var boxes = geometries.boxes;
  60983. if (boxes !== undefined && boxes !== null) {
  60984. for (index = 0, cache = boxes.length; index < cache; index++) {
  60985. var parsedBox = boxes[index];
  60986. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60987. }
  60988. }
  60989. // Spheres
  60990. var spheres = geometries.spheres;
  60991. if (spheres !== undefined && spheres !== null) {
  60992. for (index = 0, cache = spheres.length; index < cache; index++) {
  60993. var parsedSphere = spheres[index];
  60994. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60995. }
  60996. }
  60997. // Cylinders
  60998. var cylinders = geometries.cylinders;
  60999. if (cylinders !== undefined && cylinders !== null) {
  61000. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61001. var parsedCylinder = cylinders[index];
  61002. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61003. }
  61004. }
  61005. // Toruses
  61006. var toruses = geometries.toruses;
  61007. if (toruses !== undefined && toruses !== null) {
  61008. for (index = 0, cache = toruses.length; index < cache; index++) {
  61009. var parsedTorus = toruses[index];
  61010. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61011. }
  61012. }
  61013. // Grounds
  61014. var grounds = geometries.grounds;
  61015. if (grounds !== undefined && grounds !== null) {
  61016. for (index = 0, cache = grounds.length; index < cache; index++) {
  61017. var parsedGround = grounds[index];
  61018. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61019. }
  61020. }
  61021. // Planes
  61022. var planes = geometries.planes;
  61023. if (planes !== undefined && planes !== null) {
  61024. for (index = 0, cache = planes.length; index < cache; index++) {
  61025. var parsedPlane = planes[index];
  61026. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61027. }
  61028. }
  61029. // TorusKnots
  61030. var torusKnots = geometries.torusKnots;
  61031. if (torusKnots !== undefined && torusKnots !== null) {
  61032. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61033. var parsedTorusKnot = torusKnots[index];
  61034. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61035. }
  61036. }
  61037. // VertexData
  61038. var vertexData = geometries.vertexData;
  61039. if (vertexData !== undefined && vertexData !== null) {
  61040. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61041. var parsedVertexData = vertexData[index];
  61042. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61043. }
  61044. }
  61045. addedGeometry.forEach(function (g) {
  61046. if (g) {
  61047. container.geometries.push(g);
  61048. }
  61049. });
  61050. }
  61051. // Transform nodes
  61052. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61053. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61054. var parsedTransformNode = parsedData.transformNodes[index];
  61055. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61056. container.transformNodes.push(node);
  61057. }
  61058. }
  61059. // Meshes
  61060. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61061. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61062. var parsedMesh = parsedData.meshes[index];
  61063. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61064. container.meshes.push(mesh);
  61065. log += (index === 0 ? "\n\tMeshes:" : "");
  61066. log += "\n\t\t" + mesh.toString(fullDetails);
  61067. }
  61068. }
  61069. // Cameras
  61070. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61071. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61072. var parsedCamera = parsedData.cameras[index];
  61073. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61074. container.cameras.push(camera);
  61075. log += (index === 0 ? "\n\tCameras:" : "");
  61076. log += "\n\t\t" + camera.toString(fullDetails);
  61077. }
  61078. }
  61079. // Browsing all the graph to connect the dots
  61080. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61081. var camera = scene.cameras[index];
  61082. if (camera._waitingParentId) {
  61083. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61084. camera._waitingParentId = null;
  61085. }
  61086. }
  61087. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61088. var light_1 = scene.lights[index];
  61089. if (light_1 && light_1._waitingParentId) {
  61090. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61091. light_1._waitingParentId = null;
  61092. }
  61093. }
  61094. // Sounds
  61095. // TODO: add sound
  61096. var loadedSounds = [];
  61097. var loadedSound;
  61098. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61099. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61100. var parsedSound = parsedData.sounds[index];
  61101. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61102. if (!parsedSound.url)
  61103. parsedSound.url = parsedSound.name;
  61104. if (!loadedSounds[parsedSound.url]) {
  61105. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61106. loadedSounds[parsedSound.url] = loadedSound;
  61107. container.sounds.push(loadedSound);
  61108. }
  61109. else {
  61110. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61111. }
  61112. }
  61113. else {
  61114. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61115. }
  61116. }
  61117. }
  61118. loadedSounds = [];
  61119. // Connect parents & children and parse actions
  61120. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61121. var transformNode = scene.transformNodes[index];
  61122. if (transformNode._waitingParentId) {
  61123. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61124. transformNode._waitingParentId = null;
  61125. }
  61126. }
  61127. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61128. var mesh = scene.meshes[index];
  61129. if (mesh._waitingParentId) {
  61130. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61131. mesh._waitingParentId = null;
  61132. }
  61133. if (mesh._waitingActions) {
  61134. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61135. mesh._waitingActions = null;
  61136. }
  61137. }
  61138. // freeze world matrix application
  61139. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61140. var currentMesh = scene.meshes[index];
  61141. if (currentMesh._waitingFreezeWorldMatrix) {
  61142. currentMesh.freezeWorldMatrix();
  61143. currentMesh._waitingFreezeWorldMatrix = null;
  61144. }
  61145. else {
  61146. currentMesh.computeWorldMatrix(true);
  61147. }
  61148. }
  61149. // Particles Systems
  61150. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61151. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61152. var parsedParticleSystem = parsedData.particleSystems[index];
  61153. if (parsedParticleSystem.activeParticleCount) {
  61154. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61155. container.particleSystems.push(ps);
  61156. }
  61157. else {
  61158. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61159. container.particleSystems.push(ps);
  61160. }
  61161. }
  61162. }
  61163. // Lens flares
  61164. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61165. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61166. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61167. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61168. container.lensFlareSystems.push(lf);
  61169. }
  61170. }
  61171. // Shadows
  61172. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61173. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61174. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61175. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61176. container.shadowGenerators.push(sg);
  61177. }
  61178. }
  61179. // Lights exclusions / inclusions
  61180. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61181. var light_2 = scene.lights[index];
  61182. // Excluded check
  61183. if (light_2._excludedMeshesIds.length > 0) {
  61184. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61185. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61186. if (excludedMesh) {
  61187. light_2.excludedMeshes.push(excludedMesh);
  61188. }
  61189. }
  61190. light_2._excludedMeshesIds = [];
  61191. }
  61192. // Included check
  61193. if (light_2._includedOnlyMeshesIds.length > 0) {
  61194. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61195. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61196. if (includedOnlyMesh) {
  61197. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61198. }
  61199. }
  61200. light_2._includedOnlyMeshesIds = [];
  61201. }
  61202. }
  61203. // Actions (scene)
  61204. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61205. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61206. }
  61207. if (!addToScene) {
  61208. container.removeAllFromScene();
  61209. }
  61210. }
  61211. catch (err) {
  61212. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61213. if (onError) {
  61214. onError(msg, err);
  61215. }
  61216. else {
  61217. BABYLON.Tools.Log(msg);
  61218. throw err;
  61219. }
  61220. }
  61221. finally {
  61222. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61223. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61224. }
  61225. }
  61226. return container;
  61227. };
  61228. BABYLON.SceneLoader.RegisterPlugin({
  61229. name: "babylon.js",
  61230. extensions: ".babylon",
  61231. canDirectLoad: function (data) {
  61232. if (data.indexOf("babylon") !== -1) {
  61233. return true;
  61234. }
  61235. return false;
  61236. },
  61237. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61238. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61239. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61240. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61241. // and avoid problems with multiple concurrent .babylon loads.
  61242. var log = "importMesh has failed JSON parse";
  61243. try {
  61244. var parsedData = JSON.parse(data);
  61245. log = "";
  61246. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61247. if (!meshesNames) {
  61248. meshesNames = null;
  61249. }
  61250. else if (!Array.isArray(meshesNames)) {
  61251. meshesNames = [meshesNames];
  61252. }
  61253. var hierarchyIds = new Array();
  61254. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61255. var loadedSkeletonsIds = [];
  61256. var loadedMaterialsIds = [];
  61257. var index;
  61258. var cache;
  61259. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61260. var parsedMesh = parsedData.meshes[index];
  61261. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61262. if (meshesNames !== null) {
  61263. // Remove found mesh name from list.
  61264. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61265. }
  61266. //Geometry?
  61267. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61268. //does the file contain geometries?
  61269. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61270. //find the correct geometry and add it to the scene
  61271. var found = false;
  61272. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61273. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61274. return;
  61275. }
  61276. else {
  61277. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61278. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61279. switch (geometryType) {
  61280. case "boxes":
  61281. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61282. break;
  61283. case "spheres":
  61284. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61285. break;
  61286. case "cylinders":
  61287. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61288. break;
  61289. case "toruses":
  61290. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61291. break;
  61292. case "grounds":
  61293. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61294. break;
  61295. case "planes":
  61296. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61297. break;
  61298. case "torusKnots":
  61299. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61300. break;
  61301. case "vertexData":
  61302. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61303. break;
  61304. }
  61305. found = true;
  61306. }
  61307. });
  61308. }
  61309. });
  61310. if (found === false) {
  61311. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61312. }
  61313. }
  61314. }
  61315. // Material ?
  61316. if (parsedMesh.materialId) {
  61317. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61318. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61319. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61320. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61321. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61322. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61323. var subMatId = parsedMultiMaterial.materials[matIndex];
  61324. loadedMaterialsIds.push(subMatId);
  61325. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61326. if (mat) {
  61327. log += "\n\tMaterial " + mat.toString(fullDetails);
  61328. }
  61329. }
  61330. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61331. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61332. if (mmat) {
  61333. materialFound = true;
  61334. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61335. }
  61336. break;
  61337. }
  61338. }
  61339. }
  61340. if (materialFound === false) {
  61341. loadedMaterialsIds.push(parsedMesh.materialId);
  61342. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61343. if (!mat) {
  61344. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61345. }
  61346. else {
  61347. log += "\n\tMaterial " + mat.toString(fullDetails);
  61348. }
  61349. }
  61350. }
  61351. // Skeleton ?
  61352. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61353. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61354. if (skeletonAlreadyLoaded === false) {
  61355. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61356. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61357. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61358. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61359. skeletons.push(skeleton);
  61360. loadedSkeletonsIds.push(parsedSkeleton.id);
  61361. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61362. }
  61363. }
  61364. }
  61365. }
  61366. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61367. meshes.push(mesh);
  61368. log += "\n\tMesh " + mesh.toString(fullDetails);
  61369. }
  61370. }
  61371. // Connecting parents
  61372. var currentMesh;
  61373. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61374. currentMesh = scene.meshes[index];
  61375. if (currentMesh._waitingParentId) {
  61376. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61377. currentMesh._waitingParentId = null;
  61378. }
  61379. }
  61380. // freeze and compute world matrix application
  61381. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61382. currentMesh = scene.meshes[index];
  61383. if (currentMesh._waitingFreezeWorldMatrix) {
  61384. currentMesh.freezeWorldMatrix();
  61385. currentMesh._waitingFreezeWorldMatrix = null;
  61386. }
  61387. else {
  61388. currentMesh.computeWorldMatrix(true);
  61389. }
  61390. }
  61391. }
  61392. // Particles
  61393. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61394. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61395. var parsedParticleSystem = parsedData.particleSystems[index];
  61396. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61397. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61398. }
  61399. }
  61400. }
  61401. return true;
  61402. }
  61403. catch (err) {
  61404. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61405. if (onError) {
  61406. onError(msg, err);
  61407. }
  61408. else {
  61409. BABYLON.Tools.Log(msg);
  61410. throw err;
  61411. }
  61412. }
  61413. finally {
  61414. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61415. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61416. }
  61417. }
  61418. return false;
  61419. },
  61420. load: function (scene, data, rootUrl, onError) {
  61421. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61422. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61423. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61424. // and avoid problems with multiple concurrent .babylon loads.
  61425. var log = "importScene has failed JSON parse";
  61426. try {
  61427. var parsedData = JSON.parse(data);
  61428. log = "";
  61429. // Scene
  61430. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61431. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61432. }
  61433. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61434. scene.autoClear = parsedData.autoClear;
  61435. }
  61436. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61437. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61438. }
  61439. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61440. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61441. }
  61442. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61443. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61444. }
  61445. // Fog
  61446. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61447. scene.fogMode = parsedData.fogMode;
  61448. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61449. scene.fogStart = parsedData.fogStart;
  61450. scene.fogEnd = parsedData.fogEnd;
  61451. scene.fogDensity = parsedData.fogDensity;
  61452. log += "\tFog mode for scene: ";
  61453. switch (scene.fogMode) {
  61454. // getters not compiling, so using hardcoded
  61455. case 1:
  61456. log += "exp\n";
  61457. break;
  61458. case 2:
  61459. log += "exp2\n";
  61460. break;
  61461. case 3:
  61462. log += "linear\n";
  61463. break;
  61464. }
  61465. }
  61466. //Physics
  61467. if (parsedData.physicsEnabled) {
  61468. var physicsPlugin;
  61469. if (parsedData.physicsEngine === "cannon") {
  61470. physicsPlugin = new BABYLON.CannonJSPlugin();
  61471. }
  61472. else if (parsedData.physicsEngine === "oimo") {
  61473. physicsPlugin = new BABYLON.OimoJSPlugin();
  61474. }
  61475. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61476. //else - default engine, which is currently oimo
  61477. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61478. scene.enablePhysics(physicsGravity, physicsPlugin);
  61479. }
  61480. // Metadata
  61481. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61482. scene.metadata = parsedData.metadata;
  61483. }
  61484. //collisions, if defined. otherwise, default is true
  61485. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61486. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61487. }
  61488. scene.workerCollisions = !!parsedData.workerCollisions;
  61489. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61490. if (!container) {
  61491. return false;
  61492. }
  61493. if (parsedData.autoAnimate) {
  61494. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61495. }
  61496. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61497. scene.setActiveCameraByID(parsedData.activeCameraID);
  61498. }
  61499. // Environment texture
  61500. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61501. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61502. if (parsedData.createDefaultSkybox === true) {
  61503. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61504. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61505. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61506. }
  61507. }
  61508. // Finish
  61509. return true;
  61510. }
  61511. catch (err) {
  61512. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61513. if (onError) {
  61514. onError(msg, err);
  61515. }
  61516. else {
  61517. BABYLON.Tools.Log(msg);
  61518. throw err;
  61519. }
  61520. }
  61521. finally {
  61522. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61523. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61524. }
  61525. }
  61526. return false;
  61527. },
  61528. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61529. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61530. return container;
  61531. }
  61532. });
  61533. })(BABYLON || (BABYLON = {}));
  61534. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61535. var BABYLON;
  61536. (function (BABYLON) {
  61537. var FilesInput = /** @class */ (function () {
  61538. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61539. this.onProcessFileCallback = function () { return true; };
  61540. this._engine = engine;
  61541. this._currentScene = scene;
  61542. this._sceneLoadedCallback = sceneLoadedCallback;
  61543. this._progressCallback = progressCallback;
  61544. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61545. this._textureLoadingCallback = textureLoadingCallback;
  61546. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61547. this._onReloadCallback = onReloadCallback;
  61548. this._errorCallback = errorCallback;
  61549. }
  61550. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61551. var _this = this;
  61552. if (elementToMonitor) {
  61553. this._elementToMonitor = elementToMonitor;
  61554. this._dragEnterHandler = function (e) { _this.drag(e); };
  61555. this._dragOverHandler = function (e) { _this.drag(e); };
  61556. this._dropHandler = function (e) { _this.drop(e); };
  61557. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61558. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61559. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61560. }
  61561. };
  61562. FilesInput.prototype.dispose = function () {
  61563. if (!this._elementToMonitor) {
  61564. return;
  61565. }
  61566. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61567. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61568. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61569. };
  61570. FilesInput.prototype.renderFunction = function () {
  61571. if (this._additionalRenderLoopLogicCallback) {
  61572. this._additionalRenderLoopLogicCallback();
  61573. }
  61574. if (this._currentScene) {
  61575. if (this._textureLoadingCallback) {
  61576. var remaining = this._currentScene.getWaitingItemsCount();
  61577. if (remaining > 0) {
  61578. this._textureLoadingCallback(remaining);
  61579. }
  61580. }
  61581. this._currentScene.render();
  61582. }
  61583. };
  61584. FilesInput.prototype.drag = function (e) {
  61585. e.stopPropagation();
  61586. e.preventDefault();
  61587. };
  61588. FilesInput.prototype.drop = function (eventDrop) {
  61589. eventDrop.stopPropagation();
  61590. eventDrop.preventDefault();
  61591. this.loadFiles(eventDrop);
  61592. };
  61593. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61594. var _this = this;
  61595. var reader = folder.createReader();
  61596. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61597. reader.readEntries(function (entries) {
  61598. remaining.count += entries.length;
  61599. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61600. var entry = entries_1[_i];
  61601. if (entry.isFile) {
  61602. entry.file(function (file) {
  61603. file.correctName = relativePath + file.name;
  61604. files.push(file);
  61605. if (--remaining.count === 0) {
  61606. callback();
  61607. }
  61608. });
  61609. }
  61610. else if (entry.isDirectory) {
  61611. _this._traverseFolder(entry, files, remaining, callback);
  61612. }
  61613. }
  61614. if (--remaining.count) {
  61615. callback();
  61616. }
  61617. });
  61618. };
  61619. FilesInput.prototype._processFiles = function (files) {
  61620. for (var i = 0; i < files.length; i++) {
  61621. var name = files[i].correctName.toLowerCase();
  61622. var extension = name.split('.').pop();
  61623. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61624. continue;
  61625. }
  61626. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61627. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61628. this._sceneFileToLoad = files[i];
  61629. }
  61630. else {
  61631. FilesInput.FilesToLoad[name] = files[i];
  61632. }
  61633. }
  61634. };
  61635. FilesInput.prototype.loadFiles = function (event) {
  61636. var _this = this;
  61637. if (this._startingProcessingFilesCallback)
  61638. this._startingProcessingFilesCallback();
  61639. // Handling data transfer via drag'n'drop
  61640. if (event && event.dataTransfer && event.dataTransfer.files) {
  61641. this._filesToLoad = event.dataTransfer.files;
  61642. }
  61643. // Handling files from input files
  61644. if (event && event.target && event.target.files) {
  61645. this._filesToLoad = event.target.files;
  61646. }
  61647. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61648. var files_1 = new Array();
  61649. var folders = [];
  61650. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61651. for (var i = 0; i < this._filesToLoad.length; i++) {
  61652. var fileToLoad = this._filesToLoad[i];
  61653. var name_1 = fileToLoad.name.toLowerCase();
  61654. var entry = void 0;
  61655. fileToLoad.correctName = name_1;
  61656. if (items) {
  61657. var item = items[i];
  61658. if (item.getAsEntry) {
  61659. entry = item.getAsEntry();
  61660. }
  61661. else if (item.webkitGetAsEntry) {
  61662. entry = item.webkitGetAsEntry();
  61663. }
  61664. }
  61665. if (!entry) {
  61666. files_1.push(fileToLoad);
  61667. }
  61668. else {
  61669. if (entry.isDirectory) {
  61670. folders.push(entry);
  61671. }
  61672. else {
  61673. files_1.push(fileToLoad);
  61674. }
  61675. }
  61676. }
  61677. if (folders.length === 0) {
  61678. this._processFiles(files_1);
  61679. this._processReload();
  61680. }
  61681. else {
  61682. var remaining = { count: folders.length };
  61683. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61684. var folder = folders_1[_i];
  61685. this._traverseFolder(folder, files_1, remaining, function () {
  61686. _this._processFiles(files_1);
  61687. if (remaining.count === 0) {
  61688. _this._processReload();
  61689. }
  61690. });
  61691. }
  61692. }
  61693. }
  61694. };
  61695. FilesInput.prototype._processReload = function () {
  61696. if (this._onReloadCallback) {
  61697. this._onReloadCallback(this._sceneFileToLoad);
  61698. }
  61699. else {
  61700. this.reload();
  61701. }
  61702. };
  61703. FilesInput.prototype.reload = function () {
  61704. var _this = this;
  61705. // If a scene file has been provided
  61706. if (this._sceneFileToLoad) {
  61707. if (this._currentScene) {
  61708. if (BABYLON.Tools.errorsCount > 0) {
  61709. BABYLON.Tools.ClearLogCache();
  61710. }
  61711. this._engine.stopRenderLoop();
  61712. this._currentScene.dispose();
  61713. }
  61714. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61715. if (_this._progressCallback) {
  61716. _this._progressCallback(progress);
  61717. }
  61718. }).then(function (scene) {
  61719. _this._currentScene = scene;
  61720. if (_this._sceneLoadedCallback) {
  61721. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61722. }
  61723. // Wait for textures and shaders to be ready
  61724. _this._currentScene.executeWhenReady(function () {
  61725. _this._engine.runRenderLoop(function () {
  61726. _this.renderFunction();
  61727. });
  61728. });
  61729. }).catch(function (error) {
  61730. if (_this._errorCallback) {
  61731. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61732. }
  61733. });
  61734. }
  61735. else {
  61736. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61737. }
  61738. };
  61739. FilesInput.FilesToLoad = {};
  61740. return FilesInput;
  61741. }());
  61742. BABYLON.FilesInput = FilesInput;
  61743. })(BABYLON || (BABYLON = {}));
  61744. //# sourceMappingURL=babylon.filesInput.js.map
  61745. var BABYLON;
  61746. (function (BABYLON) {
  61747. /**
  61748. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61749. * The underlying implementation relies on an associative array to ensure the best performances.
  61750. * The value can be anything including 'null' but except 'undefined'
  61751. */
  61752. var StringDictionary = /** @class */ (function () {
  61753. function StringDictionary() {
  61754. this._count = 0;
  61755. this._data = {};
  61756. }
  61757. /**
  61758. * This will clear this dictionary and copy the content from the 'source' one.
  61759. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61760. * @param source the dictionary to take the content from and copy to this dictionary
  61761. */
  61762. StringDictionary.prototype.copyFrom = function (source) {
  61763. var _this = this;
  61764. this.clear();
  61765. source.forEach(function (t, v) { return _this.add(t, v); });
  61766. };
  61767. /**
  61768. * Get a value based from its key
  61769. * @param key the given key to get the matching value from
  61770. * @return the value if found, otherwise undefined is returned
  61771. */
  61772. StringDictionary.prototype.get = function (key) {
  61773. var val = this._data[key];
  61774. if (val !== undefined) {
  61775. return val;
  61776. }
  61777. return undefined;
  61778. };
  61779. /**
  61780. * Get a value from its key or add it if it doesn't exist.
  61781. * This method will ensure you that a given key/data will be present in the dictionary.
  61782. * @param key the given key to get the matching value from
  61783. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61784. * The factory will only be invoked if there's no data for the given key.
  61785. * @return the value corresponding to the key.
  61786. */
  61787. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61788. var val = this.get(key);
  61789. if (val !== undefined) {
  61790. return val;
  61791. }
  61792. val = factory(key);
  61793. if (val) {
  61794. this.add(key, val);
  61795. }
  61796. return val;
  61797. };
  61798. /**
  61799. * Get a value from its key if present in the dictionary otherwise add it
  61800. * @param key the key to get the value from
  61801. * @param val if there's no such key/value pair in the dictionary add it with this value
  61802. * @return the value corresponding to the key
  61803. */
  61804. StringDictionary.prototype.getOrAdd = function (key, val) {
  61805. var curVal = this.get(key);
  61806. if (curVal !== undefined) {
  61807. return curVal;
  61808. }
  61809. this.add(key, val);
  61810. return val;
  61811. };
  61812. /**
  61813. * Check if there's a given key in the dictionary
  61814. * @param key the key to check for
  61815. * @return true if the key is present, false otherwise
  61816. */
  61817. StringDictionary.prototype.contains = function (key) {
  61818. return this._data[key] !== undefined;
  61819. };
  61820. /**
  61821. * Add a new key and its corresponding value
  61822. * @param key the key to add
  61823. * @param value the value corresponding to the key
  61824. * @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
  61825. */
  61826. StringDictionary.prototype.add = function (key, value) {
  61827. if (this._data[key] !== undefined) {
  61828. return false;
  61829. }
  61830. this._data[key] = value;
  61831. ++this._count;
  61832. return true;
  61833. };
  61834. StringDictionary.prototype.set = function (key, value) {
  61835. if (this._data[key] === undefined) {
  61836. return false;
  61837. }
  61838. this._data[key] = value;
  61839. return true;
  61840. };
  61841. /**
  61842. * Get the element of the given key and remove it from the dictionary
  61843. * @param key
  61844. */
  61845. StringDictionary.prototype.getAndRemove = function (key) {
  61846. var val = this.get(key);
  61847. if (val !== undefined) {
  61848. delete this._data[key];
  61849. --this._count;
  61850. return val;
  61851. }
  61852. return null;
  61853. };
  61854. /**
  61855. * Remove a key/value from the dictionary.
  61856. * @param key the key to remove
  61857. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61858. */
  61859. StringDictionary.prototype.remove = function (key) {
  61860. if (this.contains(key)) {
  61861. delete this._data[key];
  61862. --this._count;
  61863. return true;
  61864. }
  61865. return false;
  61866. };
  61867. /**
  61868. * Clear the whole content of the dictionary
  61869. */
  61870. StringDictionary.prototype.clear = function () {
  61871. this._data = {};
  61872. this._count = 0;
  61873. };
  61874. Object.defineProperty(StringDictionary.prototype, "count", {
  61875. get: function () {
  61876. return this._count;
  61877. },
  61878. enumerable: true,
  61879. configurable: true
  61880. });
  61881. /**
  61882. * Execute a callback on each key/val of the dictionary.
  61883. * Note that you can remove any element in this dictionary in the callback implementation
  61884. * @param callback the callback to execute on a given key/value pair
  61885. */
  61886. StringDictionary.prototype.forEach = function (callback) {
  61887. for (var cur in this._data) {
  61888. var val = this._data[cur];
  61889. callback(cur, val);
  61890. }
  61891. };
  61892. /**
  61893. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61894. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61895. * Note that you can remove any element in this dictionary in the callback implementation
  61896. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61897. */
  61898. StringDictionary.prototype.first = function (callback) {
  61899. for (var cur in this._data) {
  61900. var val = this._data[cur];
  61901. var res = callback(cur, val);
  61902. if (res) {
  61903. return res;
  61904. }
  61905. }
  61906. return null;
  61907. };
  61908. return StringDictionary;
  61909. }());
  61910. BABYLON.StringDictionary = StringDictionary;
  61911. })(BABYLON || (BABYLON = {}));
  61912. //# sourceMappingURL=babylon.stringDictionary.js.map
  61913. var BABYLON;
  61914. (function (BABYLON) {
  61915. var Tags = /** @class */ (function () {
  61916. function Tags() {
  61917. }
  61918. Tags.EnableFor = function (obj) {
  61919. obj._tags = obj._tags || {};
  61920. obj.hasTags = function () {
  61921. return Tags.HasTags(obj);
  61922. };
  61923. obj.addTags = function (tagsString) {
  61924. return Tags.AddTagsTo(obj, tagsString);
  61925. };
  61926. obj.removeTags = function (tagsString) {
  61927. return Tags.RemoveTagsFrom(obj, tagsString);
  61928. };
  61929. obj.matchesTagsQuery = function (tagsQuery) {
  61930. return Tags.MatchesQuery(obj, tagsQuery);
  61931. };
  61932. };
  61933. Tags.DisableFor = function (obj) {
  61934. delete obj._tags;
  61935. delete obj.hasTags;
  61936. delete obj.addTags;
  61937. delete obj.removeTags;
  61938. delete obj.matchesTagsQuery;
  61939. };
  61940. Tags.HasTags = function (obj) {
  61941. if (!obj._tags) {
  61942. return false;
  61943. }
  61944. return !BABYLON.Tools.IsEmpty(obj._tags);
  61945. };
  61946. Tags.GetTags = function (obj, asString) {
  61947. if (asString === void 0) { asString = true; }
  61948. if (!obj._tags) {
  61949. return null;
  61950. }
  61951. if (asString) {
  61952. var tagsArray = [];
  61953. for (var tag in obj._tags) {
  61954. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61955. tagsArray.push(tag);
  61956. }
  61957. }
  61958. return tagsArray.join(" ");
  61959. }
  61960. else {
  61961. return obj._tags;
  61962. }
  61963. };
  61964. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61965. // a tag cannot start with '||', '&&', and '!'
  61966. // it cannot contain whitespaces
  61967. Tags.AddTagsTo = function (obj, tagsString) {
  61968. if (!tagsString) {
  61969. return;
  61970. }
  61971. if (typeof tagsString !== "string") {
  61972. return;
  61973. }
  61974. var tags = tagsString.split(" ");
  61975. tags.forEach(function (tag, index, array) {
  61976. Tags._AddTagTo(obj, tag);
  61977. });
  61978. };
  61979. Tags._AddTagTo = function (obj, tag) {
  61980. tag = tag.trim();
  61981. if (tag === "" || tag === "true" || tag === "false") {
  61982. return;
  61983. }
  61984. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61985. return;
  61986. }
  61987. Tags.EnableFor(obj);
  61988. obj._tags[tag] = true;
  61989. };
  61990. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61991. if (!Tags.HasTags(obj)) {
  61992. return;
  61993. }
  61994. var tags = tagsString.split(" ");
  61995. for (var t in tags) {
  61996. Tags._RemoveTagFrom(obj, tags[t]);
  61997. }
  61998. };
  61999. Tags._RemoveTagFrom = function (obj, tag) {
  62000. delete obj._tags[tag];
  62001. };
  62002. Tags.MatchesQuery = function (obj, tagsQuery) {
  62003. if (tagsQuery === undefined) {
  62004. return true;
  62005. }
  62006. if (tagsQuery === "") {
  62007. return Tags.HasTags(obj);
  62008. }
  62009. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62010. };
  62011. return Tags;
  62012. }());
  62013. BABYLON.Tags = Tags;
  62014. })(BABYLON || (BABYLON = {}));
  62015. //# sourceMappingURL=babylon.tags.js.map
  62016. var BABYLON;
  62017. (function (BABYLON) {
  62018. var AndOrNotEvaluator = /** @class */ (function () {
  62019. function AndOrNotEvaluator() {
  62020. }
  62021. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62022. if (!query.match(/\([^\(\)]*\)/g)) {
  62023. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62024. }
  62025. else {
  62026. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62027. // remove parenthesis
  62028. r = r.slice(1, r.length - 1);
  62029. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62030. });
  62031. }
  62032. if (query === "true") {
  62033. return true;
  62034. }
  62035. if (query === "false") {
  62036. return false;
  62037. }
  62038. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62039. };
  62040. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62041. evaluateCallback = evaluateCallback || (function (r) {
  62042. return r === "true" ? true : false;
  62043. });
  62044. var result;
  62045. var or = parenthesisContent.split("||");
  62046. for (var i in or) {
  62047. if (or.hasOwnProperty(i)) {
  62048. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62049. var and = ori.split("&&");
  62050. if (and.length > 1) {
  62051. for (var j = 0; j < and.length; ++j) {
  62052. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62053. if (andj !== "true" && andj !== "false") {
  62054. if (andj[0] === "!") {
  62055. result = !evaluateCallback(andj.substring(1));
  62056. }
  62057. else {
  62058. result = evaluateCallback(andj);
  62059. }
  62060. }
  62061. else {
  62062. result = andj === "true" ? true : false;
  62063. }
  62064. if (!result) {
  62065. ori = "false";
  62066. break;
  62067. }
  62068. }
  62069. }
  62070. if (result || ori === "true") {
  62071. result = true;
  62072. break;
  62073. }
  62074. // result equals false (or undefined)
  62075. if (ori !== "true" && ori !== "false") {
  62076. if (ori[0] === "!") {
  62077. result = !evaluateCallback(ori.substring(1));
  62078. }
  62079. else {
  62080. result = evaluateCallback(ori);
  62081. }
  62082. }
  62083. else {
  62084. result = ori === "true" ? true : false;
  62085. }
  62086. }
  62087. }
  62088. // the whole parenthesis scope is replaced by 'true' or 'false'
  62089. return result ? "true" : "false";
  62090. };
  62091. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62092. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62093. // remove whitespaces
  62094. r = r.replace(/[\s]/g, function () { return ""; });
  62095. return r.length % 2 ? "!" : "";
  62096. });
  62097. booleanString = booleanString.trim();
  62098. if (booleanString === "!true") {
  62099. booleanString = "false";
  62100. }
  62101. else if (booleanString === "!false") {
  62102. booleanString = "true";
  62103. }
  62104. return booleanString;
  62105. };
  62106. return AndOrNotEvaluator;
  62107. }());
  62108. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62109. })(BABYLON || (BABYLON = {}));
  62110. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62111. var BABYLON;
  62112. (function (BABYLON) {
  62113. var Database = /** @class */ (function () {
  62114. function Database(urlToScene, callbackManifestChecked) {
  62115. // Handling various flavors of prefixed version of IndexedDB
  62116. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62117. this.callbackManifestChecked = callbackManifestChecked;
  62118. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62119. this.db = null;
  62120. this._enableSceneOffline = false;
  62121. this._enableTexturesOffline = false;
  62122. this.manifestVersionFound = 0;
  62123. this.mustUpdateRessources = false;
  62124. this.hasReachedQuota = false;
  62125. if (!Database.IDBStorageEnabled) {
  62126. this.callbackManifestChecked(true);
  62127. }
  62128. else {
  62129. this.checkManifestFile();
  62130. }
  62131. }
  62132. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62133. get: function () {
  62134. return this._enableSceneOffline;
  62135. },
  62136. enumerable: true,
  62137. configurable: true
  62138. });
  62139. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62140. get: function () {
  62141. return this._enableTexturesOffline;
  62142. },
  62143. enumerable: true,
  62144. configurable: true
  62145. });
  62146. Database.prototype.checkManifestFile = function () {
  62147. var _this = this;
  62148. var noManifestFile = function () {
  62149. _this._enableSceneOffline = false;
  62150. _this._enableTexturesOffline = false;
  62151. _this.callbackManifestChecked(false);
  62152. };
  62153. var timeStampUsed = false;
  62154. var manifestURL = this.currentSceneUrl + ".manifest";
  62155. var xhr = new XMLHttpRequest();
  62156. if (navigator.onLine) {
  62157. // Adding a timestamp to by-pass browsers' cache
  62158. timeStampUsed = true;
  62159. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62160. }
  62161. xhr.open("GET", manifestURL, true);
  62162. xhr.addEventListener("load", function () {
  62163. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62164. try {
  62165. var manifestFile = JSON.parse(xhr.response);
  62166. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62167. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62168. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62169. _this.manifestVersionFound = manifestFile.version;
  62170. }
  62171. if (_this.callbackManifestChecked) {
  62172. _this.callbackManifestChecked(true);
  62173. }
  62174. }
  62175. catch (ex) {
  62176. noManifestFile();
  62177. }
  62178. }
  62179. else {
  62180. noManifestFile();
  62181. }
  62182. }, false);
  62183. xhr.addEventListener("error", function (event) {
  62184. if (timeStampUsed) {
  62185. timeStampUsed = false;
  62186. // Let's retry without the timeStamp
  62187. // It could fail when coupled with HTML5 Offline API
  62188. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62189. xhr.open("GET", retryManifestURL, true);
  62190. xhr.send();
  62191. }
  62192. else {
  62193. noManifestFile();
  62194. }
  62195. }, false);
  62196. try {
  62197. xhr.send();
  62198. }
  62199. catch (ex) {
  62200. BABYLON.Tools.Error("Error on XHR send request.");
  62201. this.callbackManifestChecked(false);
  62202. }
  62203. };
  62204. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62205. var _this = this;
  62206. var handleError = function () {
  62207. _this.isSupported = false;
  62208. if (errorCallback)
  62209. errorCallback();
  62210. };
  62211. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62212. // Your browser doesn't support IndexedDB
  62213. this.isSupported = false;
  62214. if (errorCallback)
  62215. errorCallback();
  62216. }
  62217. else {
  62218. // If the DB hasn't been opened or created yet
  62219. if (!this.db) {
  62220. this.hasReachedQuota = false;
  62221. this.isSupported = true;
  62222. var request = this.idbFactory.open("babylonjs", 1);
  62223. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62224. request.onerror = function (event) {
  62225. handleError();
  62226. };
  62227. // executes when a version change transaction cannot complete due to other active transactions
  62228. request.onblocked = function (event) {
  62229. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62230. handleError();
  62231. };
  62232. // DB has been opened successfully
  62233. request.onsuccess = function (event) {
  62234. _this.db = request.result;
  62235. successCallback();
  62236. };
  62237. // Initialization of the DB. Creating Scenes & Textures stores
  62238. request.onupgradeneeded = function (event) {
  62239. _this.db = (event.target).result;
  62240. if (_this.db) {
  62241. try {
  62242. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62243. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62244. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62245. }
  62246. catch (ex) {
  62247. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62248. handleError();
  62249. }
  62250. }
  62251. };
  62252. }
  62253. else {
  62254. if (successCallback)
  62255. successCallback();
  62256. }
  62257. }
  62258. };
  62259. Database.prototype.loadImageFromDB = function (url, image) {
  62260. var _this = this;
  62261. var completeURL = Database.ReturnFullUrlLocation(url);
  62262. var saveAndLoadImage = function () {
  62263. if (!_this.hasReachedQuota && _this.db !== null) {
  62264. // the texture is not yet in the DB, let's try to save it
  62265. _this._saveImageIntoDBAsync(completeURL, image);
  62266. }
  62267. else {
  62268. image.src = url;
  62269. }
  62270. };
  62271. if (!this.mustUpdateRessources) {
  62272. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62273. }
  62274. else {
  62275. saveAndLoadImage();
  62276. }
  62277. };
  62278. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62279. if (this.isSupported && this.db !== null) {
  62280. var texture;
  62281. var transaction = this.db.transaction(["textures"]);
  62282. transaction.onabort = function (event) {
  62283. image.src = url;
  62284. };
  62285. transaction.oncomplete = function (event) {
  62286. var blobTextureURL;
  62287. if (texture) {
  62288. var URL = window.URL || window.webkitURL;
  62289. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62290. image.onerror = function () {
  62291. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62292. image.src = url;
  62293. };
  62294. image.src = blobTextureURL;
  62295. }
  62296. else {
  62297. notInDBCallback();
  62298. }
  62299. };
  62300. var getRequest = transaction.objectStore("textures").get(url);
  62301. getRequest.onsuccess = function (event) {
  62302. texture = (event.target).result;
  62303. };
  62304. getRequest.onerror = function (event) {
  62305. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62306. image.src = url;
  62307. };
  62308. }
  62309. else {
  62310. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62311. image.src = url;
  62312. }
  62313. };
  62314. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62315. var _this = this;
  62316. if (this.isSupported) {
  62317. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62318. var generateBlobUrl = function () {
  62319. var blobTextureURL;
  62320. if (blob) {
  62321. var URL = window.URL || window.webkitURL;
  62322. try {
  62323. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62324. }
  62325. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62326. catch (ex) {
  62327. blobTextureURL = URL.createObjectURL(blob);
  62328. }
  62329. }
  62330. if (blobTextureURL) {
  62331. image.src = blobTextureURL;
  62332. }
  62333. };
  62334. if (Database.IsUASupportingBlobStorage) {
  62335. var xhr = new XMLHttpRequest(), blob;
  62336. xhr.open("GET", url, true);
  62337. xhr.responseType = "blob";
  62338. xhr.addEventListener("load", function () {
  62339. if (xhr.status === 200 && _this.db) {
  62340. // Blob as response (XHR2)
  62341. blob = xhr.response;
  62342. var transaction = _this.db.transaction(["textures"], "readwrite");
  62343. // the transaction could abort because of a QuotaExceededError error
  62344. transaction.onabort = function (event) {
  62345. try {
  62346. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62347. var srcElement = (event.srcElement || event.target);
  62348. var error = srcElement.error;
  62349. if (error && error.name === "QuotaExceededError") {
  62350. _this.hasReachedQuota = true;
  62351. }
  62352. }
  62353. catch (ex) { }
  62354. generateBlobUrl();
  62355. };
  62356. transaction.oncomplete = function (event) {
  62357. generateBlobUrl();
  62358. };
  62359. var newTexture = { textureUrl: url, data: blob };
  62360. try {
  62361. // Put the blob into the dabase
  62362. var addRequest = transaction.objectStore("textures").put(newTexture);
  62363. addRequest.onsuccess = function (event) {
  62364. };
  62365. addRequest.onerror = function (event) {
  62366. generateBlobUrl();
  62367. };
  62368. }
  62369. catch (ex) {
  62370. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62371. if (ex.code === 25) {
  62372. Database.IsUASupportingBlobStorage = false;
  62373. }
  62374. image.src = url;
  62375. }
  62376. }
  62377. else {
  62378. image.src = url;
  62379. }
  62380. }, false);
  62381. xhr.addEventListener("error", function (event) {
  62382. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62383. image.src = url;
  62384. }, false);
  62385. xhr.send();
  62386. }
  62387. else {
  62388. image.src = url;
  62389. }
  62390. }
  62391. else {
  62392. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62393. image.src = url;
  62394. }
  62395. };
  62396. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62397. var _this = this;
  62398. var updateVersion = function () {
  62399. // the version is not yet in the DB or we need to update it
  62400. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62401. };
  62402. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62403. };
  62404. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62405. var _this = this;
  62406. if (this.isSupported && this.db) {
  62407. var version;
  62408. try {
  62409. var transaction = this.db.transaction(["versions"]);
  62410. transaction.oncomplete = function (event) {
  62411. if (version) {
  62412. // If the version in the JSON file is > than the version in DB
  62413. if (_this.manifestVersionFound > version.data) {
  62414. _this.mustUpdateRessources = true;
  62415. updateInDBCallback();
  62416. }
  62417. else {
  62418. callback(version.data);
  62419. }
  62420. }
  62421. else {
  62422. _this.mustUpdateRessources = true;
  62423. updateInDBCallback();
  62424. }
  62425. };
  62426. transaction.onabort = function (event) {
  62427. callback(-1);
  62428. };
  62429. var getRequest = transaction.objectStore("versions").get(url);
  62430. getRequest.onsuccess = function (event) {
  62431. version = (event.target).result;
  62432. };
  62433. getRequest.onerror = function (event) {
  62434. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62435. callback(-1);
  62436. };
  62437. }
  62438. catch (ex) {
  62439. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62440. callback(-1);
  62441. }
  62442. }
  62443. else {
  62444. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62445. callback(-1);
  62446. }
  62447. };
  62448. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62449. var _this = this;
  62450. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62451. try {
  62452. // Open a transaction to the database
  62453. var transaction = this.db.transaction(["versions"], "readwrite");
  62454. // the transaction could abort because of a QuotaExceededError error
  62455. transaction.onabort = function (event) {
  62456. try {
  62457. var error = event.srcElement['error'];
  62458. if (error && error.name === "QuotaExceededError") {
  62459. _this.hasReachedQuota = true;
  62460. }
  62461. }
  62462. catch (ex) { }
  62463. callback(-1);
  62464. };
  62465. transaction.oncomplete = function (event) {
  62466. callback(_this.manifestVersionFound);
  62467. };
  62468. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62469. // Put the scene into the database
  62470. var addRequest = transaction.objectStore("versions").put(newVersion);
  62471. addRequest.onsuccess = function (event) {
  62472. };
  62473. addRequest.onerror = function (event) {
  62474. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62475. };
  62476. }
  62477. catch (ex) {
  62478. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62479. callback(-1);
  62480. }
  62481. }
  62482. else {
  62483. callback(-1);
  62484. }
  62485. };
  62486. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62487. var _this = this;
  62488. var completeUrl = Database.ReturnFullUrlLocation(url);
  62489. var saveAndLoadFile = function () {
  62490. // the scene is not yet in the DB, let's try to save it
  62491. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62492. };
  62493. this._checkVersionFromDB(completeUrl, function (version) {
  62494. if (version !== -1) {
  62495. if (!_this.mustUpdateRessources) {
  62496. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62497. }
  62498. else {
  62499. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62500. }
  62501. }
  62502. else {
  62503. if (errorCallback) {
  62504. errorCallback();
  62505. }
  62506. }
  62507. });
  62508. };
  62509. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62510. if (this.isSupported && this.db) {
  62511. var targetStore;
  62512. if (url.indexOf(".babylon") !== -1) {
  62513. targetStore = "scenes";
  62514. }
  62515. else {
  62516. targetStore = "textures";
  62517. }
  62518. var file;
  62519. var transaction = this.db.transaction([targetStore]);
  62520. transaction.oncomplete = function (event) {
  62521. if (file) {
  62522. callback(file.data);
  62523. }
  62524. else {
  62525. notInDBCallback();
  62526. }
  62527. };
  62528. transaction.onabort = function (event) {
  62529. notInDBCallback();
  62530. };
  62531. var getRequest = transaction.objectStore(targetStore).get(url);
  62532. getRequest.onsuccess = function (event) {
  62533. file = (event.target).result;
  62534. };
  62535. getRequest.onerror = function (event) {
  62536. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62537. notInDBCallback();
  62538. };
  62539. }
  62540. else {
  62541. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62542. callback();
  62543. }
  62544. };
  62545. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62546. var _this = this;
  62547. if (this.isSupported) {
  62548. var targetStore;
  62549. if (url.indexOf(".babylon") !== -1) {
  62550. targetStore = "scenes";
  62551. }
  62552. else {
  62553. targetStore = "textures";
  62554. }
  62555. // Create XHR
  62556. var xhr = new XMLHttpRequest();
  62557. var fileData;
  62558. xhr.open("GET", url, true);
  62559. if (useArrayBuffer) {
  62560. xhr.responseType = "arraybuffer";
  62561. }
  62562. if (progressCallback) {
  62563. xhr.onprogress = progressCallback;
  62564. }
  62565. xhr.addEventListener("load", function () {
  62566. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62567. // Blob as response (XHR2)
  62568. //fileData = xhr.responseText;
  62569. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62570. if (!_this.hasReachedQuota && _this.db) {
  62571. // Open a transaction to the database
  62572. var transaction = _this.db.transaction([targetStore], "readwrite");
  62573. // the transaction could abort because of a QuotaExceededError error
  62574. transaction.onabort = function (event) {
  62575. try {
  62576. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62577. var error = event.srcElement['error'];
  62578. if (error && error.name === "QuotaExceededError") {
  62579. _this.hasReachedQuota = true;
  62580. }
  62581. }
  62582. catch (ex) { }
  62583. callback(fileData);
  62584. };
  62585. transaction.oncomplete = function (event) {
  62586. callback(fileData);
  62587. };
  62588. var newFile;
  62589. if (targetStore === "scenes") {
  62590. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62591. }
  62592. else {
  62593. newFile = { textureUrl: url, data: fileData };
  62594. }
  62595. try {
  62596. // Put the scene into the database
  62597. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62598. addRequest.onsuccess = function (event) {
  62599. };
  62600. addRequest.onerror = function (event) {
  62601. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62602. };
  62603. }
  62604. catch (ex) {
  62605. callback(fileData);
  62606. }
  62607. }
  62608. else {
  62609. callback(fileData);
  62610. }
  62611. }
  62612. else {
  62613. callback();
  62614. }
  62615. }, false);
  62616. xhr.addEventListener("error", function (event) {
  62617. BABYLON.Tools.Error("error on XHR request.");
  62618. callback();
  62619. }, false);
  62620. xhr.send();
  62621. }
  62622. else {
  62623. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62624. callback();
  62625. }
  62626. };
  62627. Database.IsUASupportingBlobStorage = true;
  62628. Database.IDBStorageEnabled = true;
  62629. Database.parseURL = function (url) {
  62630. var a = document.createElement('a');
  62631. a.href = url;
  62632. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62633. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62634. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62635. return absLocation;
  62636. };
  62637. Database.ReturnFullUrlLocation = function (url) {
  62638. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62639. return (Database.parseURL(window.location.href) + url);
  62640. }
  62641. else {
  62642. return url;
  62643. }
  62644. };
  62645. return Database;
  62646. }());
  62647. BABYLON.Database = Database;
  62648. })(BABYLON || (BABYLON = {}));
  62649. //# sourceMappingURL=babylon.database.js.map
  62650. var BABYLON;
  62651. (function (BABYLON) {
  62652. var FresnelParameters = /** @class */ (function () {
  62653. function FresnelParameters() {
  62654. this._isEnabled = true;
  62655. this.leftColor = BABYLON.Color3.White();
  62656. this.rightColor = BABYLON.Color3.Black();
  62657. this.bias = 0;
  62658. this.power = 1;
  62659. }
  62660. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62661. get: function () {
  62662. return this._isEnabled;
  62663. },
  62664. set: function (value) {
  62665. if (this._isEnabled === value) {
  62666. return;
  62667. }
  62668. this._isEnabled = value;
  62669. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62670. },
  62671. enumerable: true,
  62672. configurable: true
  62673. });
  62674. FresnelParameters.prototype.clone = function () {
  62675. var newFresnelParameters = new FresnelParameters();
  62676. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62677. return newFresnelParameters;
  62678. };
  62679. FresnelParameters.prototype.serialize = function () {
  62680. var serializationObject = {};
  62681. serializationObject.isEnabled = this.isEnabled;
  62682. serializationObject.leftColor = this.leftColor;
  62683. serializationObject.rightColor = this.rightColor;
  62684. serializationObject.bias = this.bias;
  62685. serializationObject.power = this.power;
  62686. return serializationObject;
  62687. };
  62688. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62689. var fresnelParameters = new FresnelParameters();
  62690. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62691. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62692. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62693. fresnelParameters.bias = parsedFresnelParameters.bias;
  62694. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62695. return fresnelParameters;
  62696. };
  62697. return FresnelParameters;
  62698. }());
  62699. BABYLON.FresnelParameters = FresnelParameters;
  62700. })(BABYLON || (BABYLON = {}));
  62701. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62702. var BABYLON;
  62703. (function (BABYLON) {
  62704. var MultiMaterial = /** @class */ (function (_super) {
  62705. __extends(MultiMaterial, _super);
  62706. function MultiMaterial(name, scene) {
  62707. var _this = _super.call(this, name, scene, true) || this;
  62708. scene.multiMaterials.push(_this);
  62709. _this.subMaterials = new Array();
  62710. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62711. return _this;
  62712. }
  62713. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62714. get: function () {
  62715. return this._subMaterials;
  62716. },
  62717. set: function (value) {
  62718. this._subMaterials = value;
  62719. this._hookArray(value);
  62720. },
  62721. enumerable: true,
  62722. configurable: true
  62723. });
  62724. MultiMaterial.prototype._hookArray = function (array) {
  62725. var _this = this;
  62726. var oldPush = array.push;
  62727. array.push = function () {
  62728. var items = [];
  62729. for (var _i = 0; _i < arguments.length; _i++) {
  62730. items[_i] = arguments[_i];
  62731. }
  62732. var result = oldPush.apply(array, items);
  62733. _this._markAllSubMeshesAsTexturesDirty();
  62734. return result;
  62735. };
  62736. var oldSplice = array.splice;
  62737. array.splice = function (index, deleteCount) {
  62738. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62739. _this._markAllSubMeshesAsTexturesDirty();
  62740. return deleted;
  62741. };
  62742. };
  62743. // Properties
  62744. MultiMaterial.prototype.getSubMaterial = function (index) {
  62745. if (index < 0 || index >= this.subMaterials.length) {
  62746. return this.getScene().defaultMaterial;
  62747. }
  62748. return this.subMaterials[index];
  62749. };
  62750. MultiMaterial.prototype.getActiveTextures = function () {
  62751. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62752. if (subMaterial) {
  62753. return subMaterial.getActiveTextures();
  62754. }
  62755. else {
  62756. return [];
  62757. }
  62758. }));
  62759. var _a;
  62760. };
  62761. // Methods
  62762. MultiMaterial.prototype.getClassName = function () {
  62763. return "MultiMaterial";
  62764. };
  62765. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62766. for (var index = 0; index < this.subMaterials.length; index++) {
  62767. var subMaterial = this.subMaterials[index];
  62768. if (subMaterial) {
  62769. if (subMaterial.storeEffectOnSubMeshes) {
  62770. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62771. return false;
  62772. }
  62773. continue;
  62774. }
  62775. if (!subMaterial.isReady(mesh)) {
  62776. return false;
  62777. }
  62778. }
  62779. }
  62780. return true;
  62781. };
  62782. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62783. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62784. for (var index = 0; index < this.subMaterials.length; index++) {
  62785. var subMaterial = null;
  62786. var current = this.subMaterials[index];
  62787. if (cloneChildren && current) {
  62788. subMaterial = current.clone(name + "-" + current.name);
  62789. }
  62790. else {
  62791. subMaterial = this.subMaterials[index];
  62792. }
  62793. newMultiMaterial.subMaterials.push(subMaterial);
  62794. }
  62795. return newMultiMaterial;
  62796. };
  62797. MultiMaterial.prototype.serialize = function () {
  62798. var serializationObject = {};
  62799. serializationObject.name = this.name;
  62800. serializationObject.id = this.id;
  62801. if (BABYLON.Tags) {
  62802. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62803. }
  62804. serializationObject.materials = [];
  62805. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62806. var subMat = this.subMaterials[matIndex];
  62807. if (subMat) {
  62808. serializationObject.materials.push(subMat.id);
  62809. }
  62810. else {
  62811. serializationObject.materials.push(null);
  62812. }
  62813. }
  62814. return serializationObject;
  62815. };
  62816. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62817. var scene = this.getScene();
  62818. if (!scene) {
  62819. return;
  62820. }
  62821. var index = scene.multiMaterials.indexOf(this);
  62822. if (index >= 0) {
  62823. scene.multiMaterials.splice(index, 1);
  62824. }
  62825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62826. };
  62827. return MultiMaterial;
  62828. }(BABYLON.Material));
  62829. BABYLON.MultiMaterial = MultiMaterial;
  62830. })(BABYLON || (BABYLON = {}));
  62831. //# sourceMappingURL=babylon.multiMaterial.js.map
  62832. var BABYLON;
  62833. (function (BABYLON) {
  62834. var FreeCameraTouchInput = /** @class */ (function () {
  62835. function FreeCameraTouchInput() {
  62836. this._offsetX = null;
  62837. this._offsetY = null;
  62838. this._pointerPressed = new Array();
  62839. this.touchAngularSensibility = 200000.0;
  62840. this.touchMoveSensibility = 250.0;
  62841. }
  62842. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62843. var _this = this;
  62844. var previousPosition = null;
  62845. if (this._pointerInput === undefined) {
  62846. this._onLostFocus = function (evt) {
  62847. _this._offsetX = null;
  62848. _this._offsetY = null;
  62849. };
  62850. this._pointerInput = function (p, s) {
  62851. var evt = p.event;
  62852. if (evt.pointerType === "mouse") {
  62853. return;
  62854. }
  62855. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62856. if (!noPreventDefault) {
  62857. evt.preventDefault();
  62858. }
  62859. _this._pointerPressed.push(evt.pointerId);
  62860. if (_this._pointerPressed.length !== 1) {
  62861. return;
  62862. }
  62863. previousPosition = {
  62864. x: evt.clientX,
  62865. y: evt.clientY
  62866. };
  62867. }
  62868. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62869. if (!noPreventDefault) {
  62870. evt.preventDefault();
  62871. }
  62872. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62873. if (index === -1) {
  62874. return;
  62875. }
  62876. _this._pointerPressed.splice(index, 1);
  62877. if (index != 0) {
  62878. return;
  62879. }
  62880. previousPosition = null;
  62881. _this._offsetX = null;
  62882. _this._offsetY = null;
  62883. }
  62884. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62885. if (!noPreventDefault) {
  62886. evt.preventDefault();
  62887. }
  62888. if (!previousPosition) {
  62889. return;
  62890. }
  62891. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62892. if (index != 0) {
  62893. return;
  62894. }
  62895. _this._offsetX = evt.clientX - previousPosition.x;
  62896. _this._offsetY = -(evt.clientY - previousPosition.y);
  62897. }
  62898. };
  62899. }
  62900. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62901. if (this._onLostFocus) {
  62902. element.addEventListener("blur", this._onLostFocus);
  62903. }
  62904. };
  62905. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62906. if (this._pointerInput && element) {
  62907. if (this._observer) {
  62908. this.camera.getScene().onPointerObservable.remove(this._observer);
  62909. this._observer = null;
  62910. }
  62911. if (this._onLostFocus) {
  62912. element.removeEventListener("blur", this._onLostFocus);
  62913. this._onLostFocus = null;
  62914. }
  62915. this._pointerPressed = [];
  62916. this._offsetX = null;
  62917. this._offsetY = null;
  62918. }
  62919. };
  62920. FreeCameraTouchInput.prototype.checkInputs = function () {
  62921. if (this._offsetX && this._offsetY) {
  62922. var camera = this.camera;
  62923. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62924. if (this._pointerPressed.length > 1) {
  62925. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62926. }
  62927. else {
  62928. var speed = camera._computeLocalCameraSpeed();
  62929. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62930. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62931. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62932. }
  62933. }
  62934. };
  62935. FreeCameraTouchInput.prototype.getClassName = function () {
  62936. return "FreeCameraTouchInput";
  62937. };
  62938. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62939. return "touch";
  62940. };
  62941. __decorate([
  62942. BABYLON.serialize()
  62943. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62944. __decorate([
  62945. BABYLON.serialize()
  62946. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62947. return FreeCameraTouchInput;
  62948. }());
  62949. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62950. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62951. })(BABYLON || (BABYLON = {}));
  62952. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62953. var BABYLON;
  62954. (function (BABYLON) {
  62955. // We're mainly based on the logic defined into the FreeCamera code
  62956. var TouchCamera = /** @class */ (function (_super) {
  62957. __extends(TouchCamera, _super);
  62958. //-- end properties for backward compatibility for inputs
  62959. function TouchCamera(name, position, scene) {
  62960. var _this = _super.call(this, name, position, scene) || this;
  62961. _this.inputs.addTouch();
  62962. _this._setupInputs();
  62963. return _this;
  62964. }
  62965. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62966. //-- Begin properties for backward compatibility for inputs
  62967. get: function () {
  62968. var touch = this.inputs.attached["touch"];
  62969. if (touch)
  62970. return touch.touchAngularSensibility;
  62971. return 0;
  62972. },
  62973. set: function (value) {
  62974. var touch = this.inputs.attached["touch"];
  62975. if (touch)
  62976. touch.touchAngularSensibility = value;
  62977. },
  62978. enumerable: true,
  62979. configurable: true
  62980. });
  62981. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62982. get: function () {
  62983. var touch = this.inputs.attached["touch"];
  62984. if (touch)
  62985. return touch.touchMoveSensibility;
  62986. return 0;
  62987. },
  62988. set: function (value) {
  62989. var touch = this.inputs.attached["touch"];
  62990. if (touch)
  62991. touch.touchMoveSensibility = value;
  62992. },
  62993. enumerable: true,
  62994. configurable: true
  62995. });
  62996. TouchCamera.prototype.getClassName = function () {
  62997. return "TouchCamera";
  62998. };
  62999. TouchCamera.prototype._setupInputs = function () {
  63000. var mouse = this.inputs.attached["mouse"];
  63001. if (mouse) {
  63002. mouse.touchEnabled = false;
  63003. }
  63004. };
  63005. return TouchCamera;
  63006. }(BABYLON.FreeCamera));
  63007. BABYLON.TouchCamera = TouchCamera;
  63008. })(BABYLON || (BABYLON = {}));
  63009. //# sourceMappingURL=babylon.touchCamera.js.map
  63010. var BABYLON;
  63011. (function (BABYLON) {
  63012. var ProceduralTexture = /** @class */ (function (_super) {
  63013. __extends(ProceduralTexture, _super);
  63014. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63015. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63016. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63017. if (isCube === void 0) { isCube = false; }
  63018. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63019. _this.isCube = isCube;
  63020. _this.isEnabled = true;
  63021. _this._currentRefreshId = -1;
  63022. _this._refreshRate = 1;
  63023. _this._vertexBuffers = {};
  63024. _this._uniforms = new Array();
  63025. _this._samplers = new Array();
  63026. _this._textures = {};
  63027. _this._floats = {};
  63028. _this._floatsArrays = {};
  63029. _this._colors3 = {};
  63030. _this._colors4 = {};
  63031. _this._vectors2 = {};
  63032. _this._vectors3 = {};
  63033. _this._matrices = {};
  63034. _this._fallbackTextureUsed = false;
  63035. scene._proceduralTextures.push(_this);
  63036. _this._engine = scene.getEngine();
  63037. _this.name = name;
  63038. _this.isRenderTarget = true;
  63039. _this._size = size;
  63040. _this._generateMipMaps = generateMipMaps;
  63041. _this.setFragment(fragment);
  63042. _this._fallbackTexture = fallbackTexture;
  63043. if (isCube) {
  63044. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63045. _this.setFloat("face", 0);
  63046. }
  63047. else {
  63048. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63049. }
  63050. // VBO
  63051. var vertices = [];
  63052. vertices.push(1, 1);
  63053. vertices.push(-1, 1);
  63054. vertices.push(-1, -1);
  63055. vertices.push(1, -1);
  63056. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63057. _this._createIndexBuffer();
  63058. return _this;
  63059. }
  63060. ProceduralTexture.prototype._createIndexBuffer = function () {
  63061. var engine = this._engine;
  63062. // Indices
  63063. var indices = [];
  63064. indices.push(0);
  63065. indices.push(1);
  63066. indices.push(2);
  63067. indices.push(0);
  63068. indices.push(2);
  63069. indices.push(3);
  63070. this._indexBuffer = engine.createIndexBuffer(indices);
  63071. };
  63072. ProceduralTexture.prototype._rebuild = function () {
  63073. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63074. if (vb) {
  63075. vb._rebuild();
  63076. }
  63077. this._createIndexBuffer();
  63078. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63079. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63080. }
  63081. };
  63082. ProceduralTexture.prototype.reset = function () {
  63083. if (this._effect === undefined) {
  63084. return;
  63085. }
  63086. var engine = this._engine;
  63087. engine._releaseEffect(this._effect);
  63088. };
  63089. ProceduralTexture.prototype.isReady = function () {
  63090. var _this = this;
  63091. var engine = this._engine;
  63092. var shaders;
  63093. if (!this._fragment) {
  63094. return false;
  63095. }
  63096. if (this._fallbackTextureUsed) {
  63097. return true;
  63098. }
  63099. if (this._fragment.fragmentElement !== undefined) {
  63100. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63101. }
  63102. else {
  63103. shaders = { vertex: "procedural", fragment: this._fragment };
  63104. }
  63105. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63106. _this.releaseInternalTexture();
  63107. if (_this._fallbackTexture) {
  63108. _this._texture = _this._fallbackTexture._texture;
  63109. if (_this._texture) {
  63110. _this._texture.incrementReferences();
  63111. }
  63112. }
  63113. _this._fallbackTextureUsed = true;
  63114. });
  63115. return this._effect.isReady();
  63116. };
  63117. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63118. this._currentRefreshId = -1;
  63119. };
  63120. ProceduralTexture.prototype.setFragment = function (fragment) {
  63121. this._fragment = fragment;
  63122. };
  63123. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63124. get: function () {
  63125. return this._refreshRate;
  63126. },
  63127. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63128. set: function (value) {
  63129. this._refreshRate = value;
  63130. this.resetRefreshCounter();
  63131. },
  63132. enumerable: true,
  63133. configurable: true
  63134. });
  63135. ProceduralTexture.prototype._shouldRender = function () {
  63136. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63137. return false;
  63138. }
  63139. if (this._fallbackTextureUsed) {
  63140. return false;
  63141. }
  63142. if (this._currentRefreshId === -1) {
  63143. this._currentRefreshId = 1;
  63144. return true;
  63145. }
  63146. if (this.refreshRate === this._currentRefreshId) {
  63147. this._currentRefreshId = 1;
  63148. return true;
  63149. }
  63150. this._currentRefreshId++;
  63151. return false;
  63152. };
  63153. ProceduralTexture.prototype.getRenderSize = function () {
  63154. return this._size;
  63155. };
  63156. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63157. if (this._fallbackTextureUsed) {
  63158. return;
  63159. }
  63160. this.releaseInternalTexture();
  63161. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63162. };
  63163. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63164. if (this._uniforms.indexOf(uniformName) === -1) {
  63165. this._uniforms.push(uniformName);
  63166. }
  63167. };
  63168. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63169. if (this._samplers.indexOf(name) === -1) {
  63170. this._samplers.push(name);
  63171. }
  63172. this._textures[name] = texture;
  63173. return this;
  63174. };
  63175. ProceduralTexture.prototype.setFloat = function (name, value) {
  63176. this._checkUniform(name);
  63177. this._floats[name] = value;
  63178. return this;
  63179. };
  63180. ProceduralTexture.prototype.setFloats = function (name, value) {
  63181. this._checkUniform(name);
  63182. this._floatsArrays[name] = value;
  63183. return this;
  63184. };
  63185. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63186. this._checkUniform(name);
  63187. this._colors3[name] = value;
  63188. return this;
  63189. };
  63190. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63191. this._checkUniform(name);
  63192. this._colors4[name] = value;
  63193. return this;
  63194. };
  63195. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63196. this._checkUniform(name);
  63197. this._vectors2[name] = value;
  63198. return this;
  63199. };
  63200. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63201. this._checkUniform(name);
  63202. this._vectors3[name] = value;
  63203. return this;
  63204. };
  63205. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63206. this._checkUniform(name);
  63207. this._matrices[name] = value;
  63208. return this;
  63209. };
  63210. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63211. var scene = this.getScene();
  63212. if (!scene) {
  63213. return;
  63214. }
  63215. var engine = this._engine;
  63216. // Render
  63217. engine.enableEffect(this._effect);
  63218. engine.setState(false);
  63219. // Texture
  63220. for (var name in this._textures) {
  63221. this._effect.setTexture(name, this._textures[name]);
  63222. }
  63223. // Float
  63224. for (name in this._floats) {
  63225. this._effect.setFloat(name, this._floats[name]);
  63226. }
  63227. // Floats
  63228. for (name in this._floatsArrays) {
  63229. this._effect.setArray(name, this._floatsArrays[name]);
  63230. }
  63231. // Color3
  63232. for (name in this._colors3) {
  63233. this._effect.setColor3(name, this._colors3[name]);
  63234. }
  63235. // Color4
  63236. for (name in this._colors4) {
  63237. var color = this._colors4[name];
  63238. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63239. }
  63240. // Vector2
  63241. for (name in this._vectors2) {
  63242. this._effect.setVector2(name, this._vectors2[name]);
  63243. }
  63244. // Vector3
  63245. for (name in this._vectors3) {
  63246. this._effect.setVector3(name, this._vectors3[name]);
  63247. }
  63248. // Matrix
  63249. for (name in this._matrices) {
  63250. this._effect.setMatrix(name, this._matrices[name]);
  63251. }
  63252. if (!this._texture) {
  63253. return;
  63254. }
  63255. if (this.isCube) {
  63256. for (var face = 0; face < 6; face++) {
  63257. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63258. // VBOs
  63259. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63260. this._effect.setFloat("face", face);
  63261. // Clear
  63262. engine.clear(scene.clearColor, true, true, true);
  63263. // Draw order
  63264. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63265. // Mipmaps
  63266. if (face === 5) {
  63267. engine.generateMipMapsForCubemap(this._texture);
  63268. }
  63269. }
  63270. }
  63271. else {
  63272. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63273. // VBOs
  63274. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63275. // Clear
  63276. engine.clear(scene.clearColor, true, true, true);
  63277. // Draw order
  63278. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63279. }
  63280. // Unbind
  63281. engine.unBindFramebuffer(this._texture, this.isCube);
  63282. if (this.onGenerated) {
  63283. this.onGenerated();
  63284. }
  63285. };
  63286. ProceduralTexture.prototype.clone = function () {
  63287. var textureSize = this.getSize();
  63288. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63289. // Base texture
  63290. newTexture.hasAlpha = this.hasAlpha;
  63291. newTexture.level = this.level;
  63292. // RenderTarget Texture
  63293. newTexture.coordinatesMode = this.coordinatesMode;
  63294. return newTexture;
  63295. };
  63296. ProceduralTexture.prototype.dispose = function () {
  63297. var scene = this.getScene();
  63298. if (!scene) {
  63299. return;
  63300. }
  63301. var index = scene._proceduralTextures.indexOf(this);
  63302. if (index >= 0) {
  63303. scene._proceduralTextures.splice(index, 1);
  63304. }
  63305. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63306. if (vertexBuffer) {
  63307. vertexBuffer.dispose();
  63308. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63309. }
  63310. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63311. this._indexBuffer = null;
  63312. }
  63313. _super.prototype.dispose.call(this);
  63314. };
  63315. return ProceduralTexture;
  63316. }(BABYLON.Texture));
  63317. BABYLON.ProceduralTexture = ProceduralTexture;
  63318. })(BABYLON || (BABYLON = {}));
  63319. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63320. var BABYLON;
  63321. (function (BABYLON) {
  63322. var CustomProceduralTexture = /** @class */ (function (_super) {
  63323. __extends(CustomProceduralTexture, _super);
  63324. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63325. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63326. _this._animate = true;
  63327. _this._time = 0;
  63328. _this._texturePath = texturePath;
  63329. //Try to load json
  63330. _this.loadJson(texturePath);
  63331. _this.refreshRate = 1;
  63332. return _this;
  63333. }
  63334. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63335. var _this = this;
  63336. var noConfigFile = function () {
  63337. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63338. try {
  63339. _this.setFragment(_this._texturePath);
  63340. }
  63341. catch (ex) {
  63342. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63343. }
  63344. };
  63345. var configFileUrl = jsonUrl + "/config.json";
  63346. var xhr = new XMLHttpRequest();
  63347. xhr.open("GET", configFileUrl, true);
  63348. xhr.addEventListener("load", function () {
  63349. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63350. try {
  63351. _this._config = JSON.parse(xhr.response);
  63352. _this.updateShaderUniforms();
  63353. _this.updateTextures();
  63354. _this.setFragment(_this._texturePath + "/custom");
  63355. _this._animate = _this._config.animate;
  63356. _this.refreshRate = _this._config.refreshrate;
  63357. }
  63358. catch (ex) {
  63359. noConfigFile();
  63360. }
  63361. }
  63362. else {
  63363. noConfigFile();
  63364. }
  63365. }, false);
  63366. xhr.addEventListener("error", function () {
  63367. noConfigFile();
  63368. }, false);
  63369. try {
  63370. xhr.send();
  63371. }
  63372. catch (ex) {
  63373. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63374. }
  63375. };
  63376. CustomProceduralTexture.prototype.isReady = function () {
  63377. if (!_super.prototype.isReady.call(this)) {
  63378. return false;
  63379. }
  63380. for (var name in this._textures) {
  63381. var texture = this._textures[name];
  63382. if (!texture.isReady()) {
  63383. return false;
  63384. }
  63385. }
  63386. return true;
  63387. };
  63388. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63389. var scene = this.getScene();
  63390. if (this._animate && scene) {
  63391. this._time += scene.getAnimationRatio() * 0.03;
  63392. this.updateShaderUniforms();
  63393. }
  63394. _super.prototype.render.call(this, useCameraPostProcess);
  63395. };
  63396. CustomProceduralTexture.prototype.updateTextures = function () {
  63397. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63398. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63399. }
  63400. };
  63401. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63402. if (this._config) {
  63403. for (var j = 0; j < this._config.uniforms.length; j++) {
  63404. var uniform = this._config.uniforms[j];
  63405. switch (uniform.type) {
  63406. case "float":
  63407. this.setFloat(uniform.name, uniform.value);
  63408. break;
  63409. case "color3":
  63410. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63411. break;
  63412. case "color4":
  63413. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63414. break;
  63415. case "vector2":
  63416. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63417. break;
  63418. case "vector3":
  63419. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63420. break;
  63421. }
  63422. }
  63423. }
  63424. this.setFloat("time", this._time);
  63425. };
  63426. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63427. get: function () {
  63428. return this._animate;
  63429. },
  63430. set: function (value) {
  63431. this._animate = value;
  63432. },
  63433. enumerable: true,
  63434. configurable: true
  63435. });
  63436. return CustomProceduralTexture;
  63437. }(BABYLON.ProceduralTexture));
  63438. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63439. })(BABYLON || (BABYLON = {}));
  63440. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63441. var BABYLON;
  63442. (function (BABYLON) {
  63443. var FreeCameraGamepadInput = /** @class */ (function () {
  63444. function FreeCameraGamepadInput() {
  63445. this.gamepadAngularSensibility = 200;
  63446. this.gamepadMoveSensibility = 40;
  63447. // private members
  63448. this._cameraTransform = BABYLON.Matrix.Identity();
  63449. this._deltaTransform = BABYLON.Vector3.Zero();
  63450. this._vector3 = BABYLON.Vector3.Zero();
  63451. this._vector2 = BABYLON.Vector2.Zero();
  63452. }
  63453. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63454. var _this = this;
  63455. var manager = this.camera.getScene().gamepadManager;
  63456. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63457. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63458. // prioritize XBOX gamepads.
  63459. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63460. _this.gamepad = gamepad;
  63461. }
  63462. }
  63463. });
  63464. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63465. if (_this.gamepad === gamepad) {
  63466. _this.gamepad = null;
  63467. }
  63468. });
  63469. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63470. };
  63471. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63472. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63473. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63474. this.gamepad = null;
  63475. };
  63476. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63477. if (this.gamepad && this.gamepad.leftStick) {
  63478. var camera = this.camera;
  63479. var LSValues = this.gamepad.leftStick;
  63480. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63481. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63482. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63483. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63484. var RSValues = this.gamepad.rightStick;
  63485. if (RSValues) {
  63486. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63487. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63488. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63489. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63490. }
  63491. else {
  63492. RSValues = { x: 0, y: 0 };
  63493. }
  63494. if (!camera.rotationQuaternion) {
  63495. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63496. }
  63497. else {
  63498. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63499. }
  63500. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63501. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63502. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63503. camera.cameraDirection.addInPlace(this._deltaTransform);
  63504. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63505. camera.cameraRotation.addInPlace(this._vector2);
  63506. }
  63507. };
  63508. FreeCameraGamepadInput.prototype.getClassName = function () {
  63509. return "FreeCameraGamepadInput";
  63510. };
  63511. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63512. return "gamepad";
  63513. };
  63514. __decorate([
  63515. BABYLON.serialize()
  63516. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63517. __decorate([
  63518. BABYLON.serialize()
  63519. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63520. return FreeCameraGamepadInput;
  63521. }());
  63522. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63523. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63524. })(BABYLON || (BABYLON = {}));
  63525. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63526. var BABYLON;
  63527. (function (BABYLON) {
  63528. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63529. function ArcRotateCameraGamepadInput() {
  63530. this.gamepadRotationSensibility = 80;
  63531. this.gamepadMoveSensibility = 40;
  63532. }
  63533. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63534. var _this = this;
  63535. var manager = this.camera.getScene().gamepadManager;
  63536. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63537. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63538. // prioritize XBOX gamepads.
  63539. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63540. _this.gamepad = gamepad;
  63541. }
  63542. }
  63543. });
  63544. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63545. if (_this.gamepad === gamepad) {
  63546. _this.gamepad = null;
  63547. }
  63548. });
  63549. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63550. };
  63551. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63552. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63553. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63554. this.gamepad = null;
  63555. };
  63556. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63557. if (this.gamepad) {
  63558. var camera = this.camera;
  63559. var RSValues = this.gamepad.rightStick;
  63560. if (RSValues) {
  63561. if (RSValues.x != 0) {
  63562. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63563. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63564. camera.inertialAlphaOffset += normalizedRX;
  63565. }
  63566. }
  63567. if (RSValues.y != 0) {
  63568. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63569. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63570. camera.inertialBetaOffset += normalizedRY;
  63571. }
  63572. }
  63573. }
  63574. var LSValues = this.gamepad.leftStick;
  63575. if (LSValues && LSValues.y != 0) {
  63576. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63577. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63578. this.camera.inertialRadiusOffset -= normalizedLY;
  63579. }
  63580. }
  63581. }
  63582. };
  63583. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63584. return "ArcRotateCameraGamepadInput";
  63585. };
  63586. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63587. return "gamepad";
  63588. };
  63589. __decorate([
  63590. BABYLON.serialize()
  63591. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63592. __decorate([
  63593. BABYLON.serialize()
  63594. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63595. return ArcRotateCameraGamepadInput;
  63596. }());
  63597. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63598. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63599. })(BABYLON || (BABYLON = {}));
  63600. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63601. var BABYLON;
  63602. (function (BABYLON) {
  63603. var GamepadManager = /** @class */ (function () {
  63604. function GamepadManager(_scene) {
  63605. var _this = this;
  63606. this._scene = _scene;
  63607. this._babylonGamepads = [];
  63608. this._oneGamepadConnected = false;
  63609. this._isMonitoring = false;
  63610. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63611. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63612. this._gamepadEventSupported = false;
  63613. }
  63614. else {
  63615. this._gamepadEventSupported = 'GamepadEvent' in window;
  63616. this._gamepadSupport = (navigator.getGamepads ||
  63617. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63618. }
  63619. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63620. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63621. for (var i in _this._babylonGamepads) {
  63622. var gamepad = _this._babylonGamepads[i];
  63623. if (gamepad && gamepad._isConnected) {
  63624. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63625. }
  63626. }
  63627. });
  63628. this._onGamepadConnectedEvent = function (evt) {
  63629. var gamepad = evt.gamepad;
  63630. if (gamepad.index in _this._babylonGamepads) {
  63631. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63632. return;
  63633. }
  63634. }
  63635. var newGamepad;
  63636. if (_this._babylonGamepads[gamepad.index]) {
  63637. newGamepad = _this._babylonGamepads[gamepad.index];
  63638. newGamepad.browserGamepad = gamepad;
  63639. newGamepad._isConnected = true;
  63640. }
  63641. else {
  63642. newGamepad = _this._addNewGamepad(gamepad);
  63643. }
  63644. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63645. _this._startMonitoringGamepads();
  63646. };
  63647. this._onGamepadDisconnectedEvent = function (evt) {
  63648. var gamepad = evt.gamepad;
  63649. // Remove the gamepad from the list of gamepads to monitor.
  63650. for (var i in _this._babylonGamepads) {
  63651. if (_this._babylonGamepads[i].index === gamepad.index) {
  63652. var disconnectedGamepad = _this._babylonGamepads[i];
  63653. disconnectedGamepad._isConnected = false;
  63654. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63655. break;
  63656. }
  63657. }
  63658. };
  63659. if (this._gamepadSupport) {
  63660. //first add already-connected gamepads
  63661. this._updateGamepadObjects();
  63662. if (this._babylonGamepads.length) {
  63663. this._startMonitoringGamepads();
  63664. }
  63665. // Checking if the gamepad connected event is supported (like in Firefox)
  63666. if (this._gamepadEventSupported) {
  63667. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63668. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63669. }
  63670. else {
  63671. this._startMonitoringGamepads();
  63672. }
  63673. }
  63674. }
  63675. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63676. get: function () {
  63677. return this._babylonGamepads;
  63678. },
  63679. enumerable: true,
  63680. configurable: true
  63681. });
  63682. GamepadManager.prototype.getGamepadByType = function (type) {
  63683. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63684. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63685. var gamepad = _a[_i];
  63686. if (gamepad && gamepad.type === type) {
  63687. return gamepad;
  63688. }
  63689. }
  63690. return null;
  63691. };
  63692. GamepadManager.prototype.dispose = function () {
  63693. if (this._gamepadEventSupported) {
  63694. if (this._onGamepadConnectedEvent) {
  63695. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63696. }
  63697. if (this._onGamepadDisconnectedEvent) {
  63698. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63699. }
  63700. this._onGamepadConnectedEvent = null;
  63701. this._onGamepadDisconnectedEvent = null;
  63702. }
  63703. this._babylonGamepads.forEach(function (gamepad) {
  63704. gamepad.dispose();
  63705. });
  63706. this.onGamepadConnectedObservable.clear();
  63707. this.onGamepadDisconnectedObservable.clear();
  63708. this._oneGamepadConnected = false;
  63709. this._stopMonitoringGamepads();
  63710. this._babylonGamepads = [];
  63711. };
  63712. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63713. if (!this._oneGamepadConnected) {
  63714. this._oneGamepadConnected = true;
  63715. }
  63716. var newGamepad;
  63717. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63718. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63719. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63720. }
  63721. else if (gamepad.pose) {
  63722. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63723. }
  63724. else {
  63725. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63726. }
  63727. this._babylonGamepads[newGamepad.index] = newGamepad;
  63728. return newGamepad;
  63729. };
  63730. GamepadManager.prototype._startMonitoringGamepads = function () {
  63731. if (!this._isMonitoring) {
  63732. this._isMonitoring = true;
  63733. //back-comp
  63734. if (!this._scene) {
  63735. this._checkGamepadsStatus();
  63736. }
  63737. }
  63738. };
  63739. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63740. this._isMonitoring = false;
  63741. };
  63742. GamepadManager.prototype._checkGamepadsStatus = function () {
  63743. var _this = this;
  63744. // Hack to be compatible Chrome
  63745. this._updateGamepadObjects();
  63746. for (var i in this._babylonGamepads) {
  63747. var gamepad = this._babylonGamepads[i];
  63748. if (!gamepad || !gamepad.isConnected) {
  63749. continue;
  63750. }
  63751. gamepad.update();
  63752. }
  63753. if (this._isMonitoring && !this._scene) {
  63754. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63755. }
  63756. };
  63757. // This function is called only on Chrome, which does not properly support
  63758. // connection/disconnection events and forces you to recopy again the gamepad object
  63759. GamepadManager.prototype._updateGamepadObjects = function () {
  63760. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63761. for (var i = 0; i < gamepads.length; i++) {
  63762. if (gamepads[i]) {
  63763. if (!this._babylonGamepads[gamepads[i].index]) {
  63764. var newGamepad = this._addNewGamepad(gamepads[i]);
  63765. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63766. }
  63767. else {
  63768. // Forced to copy again this object for Chrome for unknown reason
  63769. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63770. if (!this._babylonGamepads[i].isConnected) {
  63771. this._babylonGamepads[i]._isConnected = true;
  63772. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63773. }
  63774. }
  63775. }
  63776. }
  63777. };
  63778. return GamepadManager;
  63779. }());
  63780. BABYLON.GamepadManager = GamepadManager;
  63781. })(BABYLON || (BABYLON = {}));
  63782. //# sourceMappingURL=babylon.gamepadManager.js.map
  63783. var BABYLON;
  63784. (function (BABYLON) {
  63785. var StickValues = /** @class */ (function () {
  63786. function StickValues(x, y) {
  63787. this.x = x;
  63788. this.y = y;
  63789. }
  63790. return StickValues;
  63791. }());
  63792. BABYLON.StickValues = StickValues;
  63793. var Gamepad = /** @class */ (function () {
  63794. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63795. if (leftStickX === void 0) { leftStickX = 0; }
  63796. if (leftStickY === void 0) { leftStickY = 1; }
  63797. if (rightStickX === void 0) { rightStickX = 2; }
  63798. if (rightStickY === void 0) { rightStickY = 3; }
  63799. this.id = id;
  63800. this.index = index;
  63801. this.browserGamepad = browserGamepad;
  63802. this._isConnected = true;
  63803. this._invertLeftStickY = false;
  63804. this.type = Gamepad.GAMEPAD;
  63805. this._leftStickAxisX = leftStickX;
  63806. this._leftStickAxisY = leftStickY;
  63807. this._rightStickAxisX = rightStickX;
  63808. this._rightStickAxisY = rightStickY;
  63809. if (this.browserGamepad.axes.length >= 2) {
  63810. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63811. }
  63812. if (this.browserGamepad.axes.length >= 4) {
  63813. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63814. }
  63815. }
  63816. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63817. get: function () {
  63818. return this._isConnected;
  63819. },
  63820. enumerable: true,
  63821. configurable: true
  63822. });
  63823. Gamepad.prototype.onleftstickchanged = function (callback) {
  63824. this._onleftstickchanged = callback;
  63825. };
  63826. Gamepad.prototype.onrightstickchanged = function (callback) {
  63827. this._onrightstickchanged = callback;
  63828. };
  63829. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63830. get: function () {
  63831. return this._leftStick;
  63832. },
  63833. set: function (newValues) {
  63834. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63835. this._onleftstickchanged(newValues);
  63836. }
  63837. this._leftStick = newValues;
  63838. },
  63839. enumerable: true,
  63840. configurable: true
  63841. });
  63842. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63843. get: function () {
  63844. return this._rightStick;
  63845. },
  63846. set: function (newValues) {
  63847. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63848. this._onrightstickchanged(newValues);
  63849. }
  63850. this._rightStick = newValues;
  63851. },
  63852. enumerable: true,
  63853. configurable: true
  63854. });
  63855. Gamepad.prototype.update = function () {
  63856. if (this._leftStick) {
  63857. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63858. if (this._invertLeftStickY) {
  63859. this.leftStick.y *= -1;
  63860. }
  63861. }
  63862. if (this._rightStick) {
  63863. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63864. }
  63865. };
  63866. Gamepad.prototype.dispose = function () {
  63867. };
  63868. Gamepad.GAMEPAD = 0;
  63869. Gamepad.GENERIC = 1;
  63870. Gamepad.XBOX = 2;
  63871. Gamepad.POSE_ENABLED = 3;
  63872. return Gamepad;
  63873. }());
  63874. BABYLON.Gamepad = Gamepad;
  63875. var GenericPad = /** @class */ (function (_super) {
  63876. __extends(GenericPad, _super);
  63877. function GenericPad(id, index, browserGamepad) {
  63878. var _this = _super.call(this, id, index, browserGamepad) || this;
  63879. _this.onButtonDownObservable = new BABYLON.Observable();
  63880. _this.onButtonUpObservable = new BABYLON.Observable();
  63881. _this.type = Gamepad.GENERIC;
  63882. _this._buttons = new Array(browserGamepad.buttons.length);
  63883. return _this;
  63884. }
  63885. GenericPad.prototype.onbuttondown = function (callback) {
  63886. this._onbuttondown = callback;
  63887. };
  63888. GenericPad.prototype.onbuttonup = function (callback) {
  63889. this._onbuttonup = callback;
  63890. };
  63891. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63892. if (newValue !== currentValue) {
  63893. if (newValue === 1) {
  63894. if (this._onbuttondown) {
  63895. this._onbuttondown(buttonIndex);
  63896. }
  63897. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63898. }
  63899. if (newValue === 0) {
  63900. if (this._onbuttonup) {
  63901. this._onbuttonup(buttonIndex);
  63902. }
  63903. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63904. }
  63905. }
  63906. return newValue;
  63907. };
  63908. GenericPad.prototype.update = function () {
  63909. _super.prototype.update.call(this);
  63910. for (var index = 0; index < this._buttons.length; index++) {
  63911. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63912. }
  63913. };
  63914. GenericPad.prototype.dispose = function () {
  63915. _super.prototype.dispose.call(this);
  63916. this.onButtonDownObservable.clear();
  63917. this.onButtonUpObservable.clear();
  63918. };
  63919. return GenericPad;
  63920. }(Gamepad));
  63921. BABYLON.GenericPad = GenericPad;
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.gamepad.js.map
  63924. var BABYLON;
  63925. (function (BABYLON) {
  63926. var Xbox360Button;
  63927. (function (Xbox360Button) {
  63928. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63929. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63930. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63931. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63932. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63933. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63934. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63935. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63936. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63937. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63938. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63939. var Xbox360Dpad;
  63940. (function (Xbox360Dpad) {
  63941. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63942. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63943. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63944. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63945. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63946. var Xbox360Pad = /** @class */ (function (_super) {
  63947. __extends(Xbox360Pad, _super);
  63948. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63949. if (xboxOne === void 0) { xboxOne = false; }
  63950. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63951. _this._leftTrigger = 0;
  63952. _this._rightTrigger = 0;
  63953. _this.onButtonDownObservable = new BABYLON.Observable();
  63954. _this.onButtonUpObservable = new BABYLON.Observable();
  63955. _this.onPadDownObservable = new BABYLON.Observable();
  63956. _this.onPadUpObservable = new BABYLON.Observable();
  63957. _this._buttonA = 0;
  63958. _this._buttonB = 0;
  63959. _this._buttonX = 0;
  63960. _this._buttonY = 0;
  63961. _this._buttonBack = 0;
  63962. _this._buttonStart = 0;
  63963. _this._buttonLB = 0;
  63964. _this._buttonRB = 0;
  63965. _this._buttonLeftStick = 0;
  63966. _this._buttonRightStick = 0;
  63967. _this._dPadUp = 0;
  63968. _this._dPadDown = 0;
  63969. _this._dPadLeft = 0;
  63970. _this._dPadRight = 0;
  63971. _this._isXboxOnePad = false;
  63972. _this.type = BABYLON.Gamepad.XBOX;
  63973. _this._isXboxOnePad = xboxOne;
  63974. return _this;
  63975. }
  63976. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63977. this._onlefttriggerchanged = callback;
  63978. };
  63979. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63980. this._onrighttriggerchanged = callback;
  63981. };
  63982. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63983. get: function () {
  63984. return this._leftTrigger;
  63985. },
  63986. set: function (newValue) {
  63987. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63988. this._onlefttriggerchanged(newValue);
  63989. }
  63990. this._leftTrigger = newValue;
  63991. },
  63992. enumerable: true,
  63993. configurable: true
  63994. });
  63995. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63996. get: function () {
  63997. return this._rightTrigger;
  63998. },
  63999. set: function (newValue) {
  64000. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64001. this._onrighttriggerchanged(newValue);
  64002. }
  64003. this._rightTrigger = newValue;
  64004. },
  64005. enumerable: true,
  64006. configurable: true
  64007. });
  64008. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64009. this._onbuttondown = callback;
  64010. };
  64011. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64012. this._onbuttonup = callback;
  64013. };
  64014. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64015. this._ondpaddown = callback;
  64016. };
  64017. Xbox360Pad.prototype.ondpadup = function (callback) {
  64018. this._ondpadup = callback;
  64019. };
  64020. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64021. if (newValue !== currentValue) {
  64022. if (newValue === 1) {
  64023. if (this._onbuttondown) {
  64024. this._onbuttondown(buttonType);
  64025. }
  64026. this.onButtonDownObservable.notifyObservers(buttonType);
  64027. }
  64028. if (newValue === 0) {
  64029. if (this._onbuttonup) {
  64030. this._onbuttonup(buttonType);
  64031. }
  64032. this.onButtonUpObservable.notifyObservers(buttonType);
  64033. }
  64034. }
  64035. return newValue;
  64036. };
  64037. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64038. if (newValue !== currentValue) {
  64039. if (newValue === 1) {
  64040. if (this._ondpaddown) {
  64041. this._ondpaddown(buttonType);
  64042. }
  64043. this.onPadDownObservable.notifyObservers(buttonType);
  64044. }
  64045. if (newValue === 0) {
  64046. if (this._ondpadup) {
  64047. this._ondpadup(buttonType);
  64048. }
  64049. this.onPadUpObservable.notifyObservers(buttonType);
  64050. }
  64051. }
  64052. return newValue;
  64053. };
  64054. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64055. get: function () {
  64056. return this._buttonA;
  64057. },
  64058. set: function (value) {
  64059. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64060. },
  64061. enumerable: true,
  64062. configurable: true
  64063. });
  64064. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64065. get: function () {
  64066. return this._buttonB;
  64067. },
  64068. set: function (value) {
  64069. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64070. },
  64071. enumerable: true,
  64072. configurable: true
  64073. });
  64074. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64075. get: function () {
  64076. return this._buttonX;
  64077. },
  64078. set: function (value) {
  64079. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64080. },
  64081. enumerable: true,
  64082. configurable: true
  64083. });
  64084. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64085. get: function () {
  64086. return this._buttonY;
  64087. },
  64088. set: function (value) {
  64089. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64090. },
  64091. enumerable: true,
  64092. configurable: true
  64093. });
  64094. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64095. get: function () {
  64096. return this._buttonStart;
  64097. },
  64098. set: function (value) {
  64099. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64100. },
  64101. enumerable: true,
  64102. configurable: true
  64103. });
  64104. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64105. get: function () {
  64106. return this._buttonBack;
  64107. },
  64108. set: function (value) {
  64109. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64110. },
  64111. enumerable: true,
  64112. configurable: true
  64113. });
  64114. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64115. get: function () {
  64116. return this._buttonLB;
  64117. },
  64118. set: function (value) {
  64119. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64120. },
  64121. enumerable: true,
  64122. configurable: true
  64123. });
  64124. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64125. get: function () {
  64126. return this._buttonRB;
  64127. },
  64128. set: function (value) {
  64129. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64135. get: function () {
  64136. return this._buttonLeftStick;
  64137. },
  64138. set: function (value) {
  64139. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64140. },
  64141. enumerable: true,
  64142. configurable: true
  64143. });
  64144. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64145. get: function () {
  64146. return this._buttonRightStick;
  64147. },
  64148. set: function (value) {
  64149. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64150. },
  64151. enumerable: true,
  64152. configurable: true
  64153. });
  64154. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64155. get: function () {
  64156. return this._dPadUp;
  64157. },
  64158. set: function (value) {
  64159. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64160. },
  64161. enumerable: true,
  64162. configurable: true
  64163. });
  64164. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64165. get: function () {
  64166. return this._dPadDown;
  64167. },
  64168. set: function (value) {
  64169. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64170. },
  64171. enumerable: true,
  64172. configurable: true
  64173. });
  64174. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64175. get: function () {
  64176. return this._dPadLeft;
  64177. },
  64178. set: function (value) {
  64179. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64180. },
  64181. enumerable: true,
  64182. configurable: true
  64183. });
  64184. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64185. get: function () {
  64186. return this._dPadRight;
  64187. },
  64188. set: function (value) {
  64189. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64190. },
  64191. enumerable: true,
  64192. configurable: true
  64193. });
  64194. Xbox360Pad.prototype.update = function () {
  64195. _super.prototype.update.call(this);
  64196. if (this._isXboxOnePad) {
  64197. this.buttonA = this.browserGamepad.buttons[0].value;
  64198. this.buttonB = this.browserGamepad.buttons[1].value;
  64199. this.buttonX = this.browserGamepad.buttons[2].value;
  64200. this.buttonY = this.browserGamepad.buttons[3].value;
  64201. this.buttonLB = this.browserGamepad.buttons[4].value;
  64202. this.buttonRB = this.browserGamepad.buttons[5].value;
  64203. this.leftTrigger = this.browserGamepad.axes[2];
  64204. this.rightTrigger = this.browserGamepad.axes[5];
  64205. this.buttonBack = this.browserGamepad.buttons[9].value;
  64206. this.buttonStart = this.browserGamepad.buttons[8].value;
  64207. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64208. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64209. this.dPadUp = this.browserGamepad.buttons[11].value;
  64210. this.dPadDown = this.browserGamepad.buttons[12].value;
  64211. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64212. this.dPadRight = this.browserGamepad.buttons[14].value;
  64213. }
  64214. else {
  64215. this.buttonA = this.browserGamepad.buttons[0].value;
  64216. this.buttonB = this.browserGamepad.buttons[1].value;
  64217. this.buttonX = this.browserGamepad.buttons[2].value;
  64218. this.buttonY = this.browserGamepad.buttons[3].value;
  64219. this.buttonLB = this.browserGamepad.buttons[4].value;
  64220. this.buttonRB = this.browserGamepad.buttons[5].value;
  64221. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64222. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64223. this.buttonBack = this.browserGamepad.buttons[8].value;
  64224. this.buttonStart = this.browserGamepad.buttons[9].value;
  64225. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64226. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64227. this.dPadUp = this.browserGamepad.buttons[12].value;
  64228. this.dPadDown = this.browserGamepad.buttons[13].value;
  64229. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64230. this.dPadRight = this.browserGamepad.buttons[15].value;
  64231. }
  64232. };
  64233. Xbox360Pad.prototype.dispose = function () {
  64234. _super.prototype.dispose.call(this);
  64235. this.onButtonDownObservable.clear();
  64236. this.onButtonUpObservable.clear();
  64237. this.onPadDownObservable.clear();
  64238. this.onPadUpObservable.clear();
  64239. };
  64240. return Xbox360Pad;
  64241. }(BABYLON.Gamepad));
  64242. BABYLON.Xbox360Pad = Xbox360Pad;
  64243. })(BABYLON || (BABYLON = {}));
  64244. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64245. var BABYLON;
  64246. (function (BABYLON) {
  64247. var PoseEnabledControllerType;
  64248. (function (PoseEnabledControllerType) {
  64249. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64250. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64251. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64252. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64253. /**
  64254. * Google Daydream
  64255. */
  64256. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64257. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64258. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64259. var PoseEnabledControllerHelper = /** @class */ (function () {
  64260. function PoseEnabledControllerHelper() {
  64261. }
  64262. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64263. // Oculus Touch
  64264. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64265. return new BABYLON.OculusTouchController(vrGamepad);
  64266. }
  64267. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64268. return new BABYLON.WindowsMotionController(vrGamepad);
  64269. }
  64270. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64271. return new BABYLON.ViveController(vrGamepad);
  64272. }
  64273. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64274. return new BABYLON.GearVRController(vrGamepad);
  64275. }
  64276. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64277. return new BABYLON.DaydreamController(vrGamepad);
  64278. }
  64279. else {
  64280. return new BABYLON.GenericController(vrGamepad);
  64281. }
  64282. };
  64283. return PoseEnabledControllerHelper;
  64284. }());
  64285. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64286. var PoseEnabledController = /** @class */ (function (_super) {
  64287. __extends(PoseEnabledController, _super);
  64288. function PoseEnabledController(browserGamepad) {
  64289. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64290. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64291. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64292. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64293. // Represents device position and rotation in babylon space
  64294. _this.devicePosition = BABYLON.Vector3.Zero();
  64295. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64296. _this.deviceScaleFactor = 1;
  64297. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64298. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64299. _this._workingMatrix = BABYLON.Matrix.Identity();
  64300. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64301. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64302. _this.position = BABYLON.Vector3.Zero();
  64303. _this.rotationQuaternion = new BABYLON.Quaternion();
  64304. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64305. _this._calculatedRotation = new BABYLON.Quaternion();
  64306. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64307. return _this;
  64308. }
  64309. PoseEnabledController.prototype.update = function () {
  64310. _super.prototype.update.call(this);
  64311. var pose = this.browserGamepad.pose;
  64312. this.updateFromDevice(pose);
  64313. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64314. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64315. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64316. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64317. if (this._mesh) {
  64318. this._mesh.position.copyFrom(this.devicePosition);
  64319. if (this._mesh.rotationQuaternion) {
  64320. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64321. }
  64322. }
  64323. };
  64324. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64325. if (poseData) {
  64326. this.rawPose = poseData;
  64327. if (poseData.position) {
  64328. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64329. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64330. this._deviceRoomPosition.z *= -1;
  64331. }
  64332. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64333. this._calculatedPosition.addInPlace(this.position);
  64334. }
  64335. var pose = this.rawPose;
  64336. if (poseData.orientation && pose.orientation) {
  64337. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64338. if (this._mesh) {
  64339. if (this._mesh.getScene().useRightHandedSystem) {
  64340. this._deviceRoomRotationQuaternion.z *= -1;
  64341. this._deviceRoomRotationQuaternion.w *= -1;
  64342. }
  64343. else {
  64344. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64345. }
  64346. }
  64347. // if the camera is set, rotate to the camera's rotation
  64348. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64349. }
  64350. }
  64351. };
  64352. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64353. if (this._mesh) {
  64354. this._mesh.parent = null;
  64355. }
  64356. this._mesh = mesh;
  64357. if (this._poseControlledCamera) {
  64358. this._mesh.parent = this._poseControlledCamera;
  64359. }
  64360. if (!this._mesh.rotationQuaternion) {
  64361. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64362. }
  64363. };
  64364. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64365. this._poseControlledCamera = camera;
  64366. if (this._mesh) {
  64367. this._mesh.parent = this._poseControlledCamera;
  64368. }
  64369. };
  64370. PoseEnabledController.prototype.dispose = function () {
  64371. if (this._mesh) {
  64372. this._mesh.dispose();
  64373. }
  64374. this._mesh = null;
  64375. _super.prototype.dispose.call(this);
  64376. };
  64377. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64378. get: function () {
  64379. return this._mesh;
  64380. },
  64381. enumerable: true,
  64382. configurable: true
  64383. });
  64384. PoseEnabledController.prototype.getForwardRay = function (length) {
  64385. if (length === void 0) { length = 100; }
  64386. if (!this.mesh) {
  64387. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64388. }
  64389. var m = this.mesh.getWorldMatrix();
  64390. var origin = m.getTranslation();
  64391. var forward = new BABYLON.Vector3(0, 0, -1);
  64392. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64393. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64394. return new BABYLON.Ray(origin, direction, length);
  64395. };
  64396. return PoseEnabledController;
  64397. }(BABYLON.Gamepad));
  64398. BABYLON.PoseEnabledController = PoseEnabledController;
  64399. })(BABYLON || (BABYLON = {}));
  64400. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64401. var BABYLON;
  64402. (function (BABYLON) {
  64403. var WebVRController = /** @class */ (function (_super) {
  64404. __extends(WebVRController, _super);
  64405. function WebVRController(vrGamepad) {
  64406. var _this = _super.call(this, vrGamepad) || this;
  64407. // Observables
  64408. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64409. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64410. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64411. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64412. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64413. _this.pad = { x: 0, y: 0 };
  64414. // avoid GC, store state in a tmp object
  64415. _this._changes = {
  64416. pressChanged: false,
  64417. touchChanged: false,
  64418. valueChanged: false,
  64419. changed: false
  64420. };
  64421. _this._buttons = new Array(vrGamepad.buttons.length);
  64422. _this.hand = vrGamepad.hand;
  64423. return _this;
  64424. }
  64425. WebVRController.prototype.onButtonStateChange = function (callback) {
  64426. this._onButtonStateChange = callback;
  64427. };
  64428. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64429. get: function () {
  64430. return this._defaultModel;
  64431. },
  64432. enumerable: true,
  64433. configurable: true
  64434. });
  64435. WebVRController.prototype.update = function () {
  64436. _super.prototype.update.call(this);
  64437. for (var index = 0; index < this._buttons.length; index++) {
  64438. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64439. }
  64440. ;
  64441. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64442. this.pad.x = this.leftStick.x;
  64443. this.pad.y = this.leftStick.y;
  64444. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64445. }
  64446. };
  64447. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64448. if (!newState) {
  64449. newState = {
  64450. pressed: false,
  64451. touched: false,
  64452. value: 0
  64453. };
  64454. }
  64455. if (!currentState) {
  64456. this._buttons[buttonIndex] = {
  64457. pressed: newState.pressed,
  64458. touched: newState.touched,
  64459. value: newState.value
  64460. };
  64461. return;
  64462. }
  64463. this._checkChanges(newState, currentState);
  64464. if (this._changes.changed) {
  64465. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64466. this._handleButtonChange(buttonIndex, newState, this._changes);
  64467. }
  64468. this._buttons[buttonIndex].pressed = newState.pressed;
  64469. this._buttons[buttonIndex].touched = newState.touched;
  64470. // oculus triggers are never 0, thou not touched.
  64471. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64472. };
  64473. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64474. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64475. this._changes.touchChanged = newState.touched !== currentState.touched;
  64476. this._changes.valueChanged = newState.value !== currentState.value;
  64477. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64478. return this._changes;
  64479. };
  64480. WebVRController.prototype.dispose = function () {
  64481. _super.prototype.dispose.call(this);
  64482. this.onTriggerStateChangedObservable.clear();
  64483. this.onMainButtonStateChangedObservable.clear();
  64484. this.onSecondaryButtonStateChangedObservable.clear();
  64485. this.onPadStateChangedObservable.clear();
  64486. this.onPadValuesChangedObservable.clear();
  64487. };
  64488. return WebVRController;
  64489. }(BABYLON.PoseEnabledController));
  64490. BABYLON.WebVRController = WebVRController;
  64491. })(BABYLON || (BABYLON = {}));
  64492. //# sourceMappingURL=babylon.webVRController.js.map
  64493. var BABYLON;
  64494. (function (BABYLON) {
  64495. var OculusTouchController = /** @class */ (function (_super) {
  64496. __extends(OculusTouchController, _super);
  64497. function OculusTouchController(vrGamepad) {
  64498. var _this = _super.call(this, vrGamepad) || this;
  64499. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64500. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64501. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64502. return _this;
  64503. }
  64504. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64505. var _this = this;
  64506. var meshName;
  64507. // Hand
  64508. if (this.hand === 'left') {
  64509. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64510. }
  64511. else {
  64512. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64513. }
  64514. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64515. /*
  64516. Parent Mesh name: oculus_touch_left
  64517. - body
  64518. - trigger
  64519. - thumbstick
  64520. - grip
  64521. - button_y
  64522. - button_x
  64523. - button_enter
  64524. */
  64525. _this._defaultModel = newMeshes[1];
  64526. _this.attachToMesh(_this._defaultModel);
  64527. if (meshLoaded) {
  64528. meshLoaded(_this._defaultModel);
  64529. }
  64530. });
  64531. };
  64532. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64533. // helper getters for left and right hand.
  64534. get: function () {
  64535. if (this.hand === 'right') {
  64536. return this.onMainButtonStateChangedObservable;
  64537. }
  64538. else {
  64539. throw new Error('No A button on left hand');
  64540. }
  64541. },
  64542. enumerable: true,
  64543. configurable: true
  64544. });
  64545. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64546. get: function () {
  64547. if (this.hand === 'right') {
  64548. return this.onSecondaryButtonStateChangedObservable;
  64549. }
  64550. else {
  64551. throw new Error('No B button on left hand');
  64552. }
  64553. },
  64554. enumerable: true,
  64555. configurable: true
  64556. });
  64557. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64558. get: function () {
  64559. if (this.hand === 'left') {
  64560. return this.onMainButtonStateChangedObservable;
  64561. }
  64562. else {
  64563. throw new Error('No X button on right hand');
  64564. }
  64565. },
  64566. enumerable: true,
  64567. configurable: true
  64568. });
  64569. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64570. get: function () {
  64571. if (this.hand === 'left') {
  64572. return this.onSecondaryButtonStateChangedObservable;
  64573. }
  64574. else {
  64575. throw new Error('No Y button on right hand');
  64576. }
  64577. },
  64578. enumerable: true,
  64579. configurable: true
  64580. });
  64581. /*
  64582. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64583. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64584. 2) secondary trigger (same)
  64585. 3) A (right) X (left), touch, pressed = value
  64586. 4) B / Y
  64587. 5) thumb rest
  64588. */
  64589. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64590. var notifyObject = state; //{ state: state, changes: changes };
  64591. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64592. switch (buttonIdx) {
  64593. case 0:
  64594. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64595. return;
  64596. case 1:// index trigger
  64597. if (this._defaultModel) {
  64598. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64599. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64600. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64601. }
  64602. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64603. return;
  64604. case 2:// secondary trigger
  64605. if (this._defaultModel) {
  64606. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64607. }
  64608. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64609. return;
  64610. case 3:
  64611. if (this._defaultModel) {
  64612. if (notifyObject.pressed) {
  64613. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64614. }
  64615. else {
  64616. (this._defaultModel.getChildren()[1]).position.y = 0;
  64617. }
  64618. }
  64619. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64620. return;
  64621. case 4:
  64622. if (this._defaultModel) {
  64623. if (notifyObject.pressed) {
  64624. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64625. }
  64626. else {
  64627. (this._defaultModel.getChildren()[2]).position.y = 0;
  64628. }
  64629. }
  64630. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64631. return;
  64632. case 5:
  64633. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64634. return;
  64635. }
  64636. };
  64637. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64638. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64639. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64640. return OculusTouchController;
  64641. }(BABYLON.WebVRController));
  64642. BABYLON.OculusTouchController = OculusTouchController;
  64643. })(BABYLON || (BABYLON = {}));
  64644. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64645. var BABYLON;
  64646. (function (BABYLON) {
  64647. var ViveController = /** @class */ (function (_super) {
  64648. __extends(ViveController, _super);
  64649. function ViveController(vrGamepad) {
  64650. var _this = _super.call(this, vrGamepad) || this;
  64651. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64652. _this._invertLeftStickY = true;
  64653. return _this;
  64654. }
  64655. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64656. var _this = this;
  64657. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64658. /*
  64659. Parent Mesh name: ViveWand
  64660. - body
  64661. - r_gripper
  64662. - l_gripper
  64663. - menu_button
  64664. - system_button
  64665. - trackpad
  64666. - trigger
  64667. - LED
  64668. */
  64669. _this._defaultModel = newMeshes[1];
  64670. _this.attachToMesh(_this._defaultModel);
  64671. if (meshLoaded) {
  64672. meshLoaded(_this._defaultModel);
  64673. }
  64674. });
  64675. };
  64676. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64677. get: function () {
  64678. return this.onMainButtonStateChangedObservable;
  64679. },
  64680. enumerable: true,
  64681. configurable: true
  64682. });
  64683. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64684. get: function () {
  64685. return this.onMainButtonStateChangedObservable;
  64686. },
  64687. enumerable: true,
  64688. configurable: true
  64689. });
  64690. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64691. get: function () {
  64692. return this.onSecondaryButtonStateChangedObservable;
  64693. },
  64694. enumerable: true,
  64695. configurable: true
  64696. });
  64697. /**
  64698. * Vive mapping:
  64699. * 0: touchpad
  64700. * 1: trigger
  64701. * 2: left AND right buttons
  64702. * 3: menu button
  64703. */
  64704. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64705. var notifyObject = state; //{ state: state, changes: changes };
  64706. switch (buttonIdx) {
  64707. case 0:
  64708. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64709. return;
  64710. case 1:// index trigger
  64711. if (this._defaultModel) {
  64712. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64713. }
  64714. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64715. return;
  64716. case 2:// left AND right button
  64717. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64718. return;
  64719. case 3:
  64720. if (this._defaultModel) {
  64721. if (notifyObject.pressed) {
  64722. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64723. }
  64724. else {
  64725. (this._defaultModel.getChildren()[2]).position.y = 0;
  64726. }
  64727. }
  64728. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64729. return;
  64730. }
  64731. };
  64732. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64733. ViveController.MODEL_FILENAME = 'wand.babylon';
  64734. return ViveController;
  64735. }(BABYLON.WebVRController));
  64736. BABYLON.ViveController = ViveController;
  64737. })(BABYLON || (BABYLON = {}));
  64738. //# sourceMappingURL=babylon.viveController.js.map
  64739. var BABYLON;
  64740. (function (BABYLON) {
  64741. var GenericController = /** @class */ (function (_super) {
  64742. __extends(GenericController, _super);
  64743. function GenericController(vrGamepad) {
  64744. return _super.call(this, vrGamepad) || this;
  64745. }
  64746. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64747. var _this = this;
  64748. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64749. _this._defaultModel = newMeshes[1];
  64750. _this.attachToMesh(_this._defaultModel);
  64751. if (meshLoaded) {
  64752. meshLoaded(_this._defaultModel);
  64753. }
  64754. });
  64755. };
  64756. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64757. console.log("Button id: " + buttonIdx + "state: ");
  64758. console.dir(state);
  64759. };
  64760. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64761. GenericController.MODEL_FILENAME = 'generic.babylon';
  64762. return GenericController;
  64763. }(BABYLON.WebVRController));
  64764. BABYLON.GenericController = GenericController;
  64765. })(BABYLON || (BABYLON = {}));
  64766. //# sourceMappingURL=babylon.genericController.js.map
  64767. var BABYLON;
  64768. (function (BABYLON) {
  64769. var LoadedMeshInfo = /** @class */ (function () {
  64770. function LoadedMeshInfo() {
  64771. this.buttonMeshes = {};
  64772. this.axisMeshes = {};
  64773. }
  64774. return LoadedMeshInfo;
  64775. }());
  64776. var WindowsMotionController = /** @class */ (function (_super) {
  64777. __extends(WindowsMotionController, _super);
  64778. function WindowsMotionController(vrGamepad) {
  64779. var _this = _super.call(this, vrGamepad) || this;
  64780. _this._mapping = {
  64781. // Semantic button names
  64782. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64783. // A mapping of the button name to glTF model node name
  64784. // that should be transformed by button value.
  64785. buttonMeshNames: {
  64786. 'trigger': 'SELECT',
  64787. 'menu': 'MENU',
  64788. 'grip': 'GRASP',
  64789. 'thumbstick': 'THUMBSTICK_PRESS',
  64790. 'trackpad': 'TOUCHPAD_PRESS'
  64791. },
  64792. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64793. buttonObservableNames: {
  64794. 'trigger': 'onTriggerStateChangedObservable',
  64795. 'menu': 'onSecondaryButtonStateChangedObservable',
  64796. 'grip': 'onMainButtonStateChangedObservable',
  64797. 'thumbstick': 'onPadStateChangedObservable',
  64798. 'trackpad': 'onTrackpadChangedObservable'
  64799. },
  64800. // A mapping of the axis name to glTF model node name
  64801. // that should be transformed by axis value.
  64802. // This array mirrors the browserGamepad.axes array, such that
  64803. // the mesh corresponding to axis 0 is in this array index 0.
  64804. axisMeshNames: [
  64805. 'THUMBSTICK_X',
  64806. 'THUMBSTICK_Y',
  64807. 'TOUCHPAD_TOUCH_X',
  64808. 'TOUCHPAD_TOUCH_Y'
  64809. ],
  64810. pointingPoseMeshName: 'POINTING_POSE'
  64811. };
  64812. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64813. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64814. _this.trackpad = { x: 0, y: 0 };
  64815. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64816. _this._loadedMeshInfo = null;
  64817. return _this;
  64818. }
  64819. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64820. get: function () {
  64821. return this.onTriggerStateChangedObservable;
  64822. },
  64823. enumerable: true,
  64824. configurable: true
  64825. });
  64826. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64827. get: function () {
  64828. return this.onSecondaryButtonStateChangedObservable;
  64829. },
  64830. enumerable: true,
  64831. configurable: true
  64832. });
  64833. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64834. get: function () {
  64835. return this.onMainButtonStateChangedObservable;
  64836. },
  64837. enumerable: true,
  64838. configurable: true
  64839. });
  64840. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64841. get: function () {
  64842. return this.onPadStateChangedObservable;
  64843. },
  64844. enumerable: true,
  64845. configurable: true
  64846. });
  64847. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64848. get: function () {
  64849. return this.onTrackpadChangedObservable;
  64850. },
  64851. enumerable: true,
  64852. configurable: true
  64853. });
  64854. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64855. get: function () {
  64856. return this.onTrackpadValuesChangedObservable;
  64857. },
  64858. enumerable: true,
  64859. configurable: true
  64860. });
  64861. /**
  64862. * Called once per frame by the engine.
  64863. */
  64864. WindowsMotionController.prototype.update = function () {
  64865. _super.prototype.update.call(this);
  64866. // Only need to animate axes if there is a loaded mesh
  64867. if (this._loadedMeshInfo) {
  64868. if (this.browserGamepad.axes) {
  64869. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64870. this.trackpad.x = this.browserGamepad["axes"][2];
  64871. this.trackpad.y = this.browserGamepad["axes"][3];
  64872. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64873. }
  64874. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64875. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64876. }
  64877. }
  64878. }
  64879. };
  64880. /**
  64881. * Called once for each button that changed state since the last frame
  64882. * @param buttonIdx Which button index changed
  64883. * @param state New state of the button
  64884. * @param changes Which properties on the state changed since last frame
  64885. */
  64886. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64887. var buttonName = this._mapping.buttons[buttonIdx];
  64888. if (!buttonName) {
  64889. return;
  64890. }
  64891. // Only emit events for buttons that we know how to map from index to name
  64892. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64893. if (observable) {
  64894. observable.notifyObservers(state);
  64895. }
  64896. this.lerpButtonTransform(buttonName, state.value);
  64897. };
  64898. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64899. // If there is no loaded mesh, there is nothing to transform.
  64900. if (!this._loadedMeshInfo) {
  64901. return;
  64902. }
  64903. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64904. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64905. return;
  64906. }
  64907. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64908. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64909. };
  64910. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64911. if (!this._loadedMeshInfo) {
  64912. return;
  64913. }
  64914. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64915. if (!meshInfo) {
  64916. return;
  64917. }
  64918. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64919. return;
  64920. }
  64921. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64922. var lerpValue = axisValue * 0.5 + 0.5;
  64923. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64924. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64925. };
  64926. /**
  64927. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64928. * @param scene scene in which to add meshes
  64929. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64930. */
  64931. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64932. var _this = this;
  64933. if (forceDefault === void 0) { forceDefault = false; }
  64934. var path;
  64935. var filename;
  64936. // Checking if GLB loader is present
  64937. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64938. // Determine the device specific folder based on the ID suffix
  64939. var device = 'default';
  64940. if (this.id && !forceDefault) {
  64941. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64942. device = ((match && match[0]) || device);
  64943. }
  64944. // Hand
  64945. if (this.hand === 'left') {
  64946. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64947. }
  64948. else {
  64949. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64950. }
  64951. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64952. }
  64953. else {
  64954. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64955. path = BABYLON.GenericController.MODEL_BASE_URL;
  64956. filename = BABYLON.GenericController.MODEL_FILENAME;
  64957. }
  64958. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64959. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64960. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64961. if (!_this._loadedMeshInfo) {
  64962. return;
  64963. }
  64964. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64965. _this.attachToMesh(_this._defaultModel);
  64966. if (meshLoaded) {
  64967. meshLoaded(_this._defaultModel);
  64968. }
  64969. }, null, function (scene, message) {
  64970. BABYLON.Tools.Log(message);
  64971. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64972. if (!forceDefault) {
  64973. _this.initControllerMesh(scene, meshLoaded, true);
  64974. }
  64975. });
  64976. };
  64977. /**
  64978. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64979. * can be transformed by button presses and axes values, based on this._mapping.
  64980. *
  64981. * @param scene scene in which the meshes exist
  64982. * @param meshes list of meshes that make up the controller model to process
  64983. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64984. */
  64985. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64986. var loadedMeshInfo = null;
  64987. // Create a new mesh to contain the glTF hierarchy
  64988. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64989. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64990. var childMesh = null;
  64991. for (var i = 0; i < meshes.length; i++) {
  64992. var mesh = meshes[i];
  64993. if (!mesh.parent) {
  64994. // Exclude controller meshes from picking results
  64995. mesh.isPickable = false;
  64996. // Handle root node, attach to the new parentMesh
  64997. childMesh = mesh;
  64998. break;
  64999. }
  65000. }
  65001. if (childMesh) {
  65002. childMesh.setParent(parentMesh);
  65003. // Create our mesh info. Note that this method will always return non-null.
  65004. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65005. }
  65006. else {
  65007. BABYLON.Tools.Warn('Could not find root node in model file.');
  65008. }
  65009. return loadedMeshInfo;
  65010. };
  65011. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65012. var loadedMeshInfo = new LoadedMeshInfo();
  65013. var i;
  65014. loadedMeshInfo.rootNode = rootNode;
  65015. // Reset the caches
  65016. loadedMeshInfo.buttonMeshes = {};
  65017. loadedMeshInfo.axisMeshes = {};
  65018. // Button Meshes
  65019. for (i = 0; i < this._mapping.buttons.length; i++) {
  65020. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65021. if (!buttonMeshName) {
  65022. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65023. continue;
  65024. }
  65025. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65026. if (!buttonMesh) {
  65027. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65028. continue;
  65029. }
  65030. var buttonMeshInfo = {
  65031. index: i,
  65032. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65033. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65034. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65035. };
  65036. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65037. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65038. }
  65039. else {
  65040. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65041. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65042. '(VALUE: ' + !!buttonMeshInfo.value +
  65043. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65044. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65045. ')');
  65046. }
  65047. }
  65048. // Axis Meshes
  65049. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65050. var axisMeshName = this._mapping.axisMeshNames[i];
  65051. if (!axisMeshName) {
  65052. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65053. continue;
  65054. }
  65055. var axisMesh = getChildByName(rootNode, axisMeshName);
  65056. if (!axisMesh) {
  65057. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65058. continue;
  65059. }
  65060. var axisMeshInfo = {
  65061. index: i,
  65062. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65063. min: getImmediateChildByName(axisMesh, 'MIN'),
  65064. max: getImmediateChildByName(axisMesh, 'MAX')
  65065. };
  65066. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65067. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65068. }
  65069. else {
  65070. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65071. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65072. '(VALUE: ' + !!axisMeshInfo.value +
  65073. ', MIN: ' + !!axisMeshInfo.min +
  65074. ', MAX:' + !!axisMeshInfo.max +
  65075. ')');
  65076. }
  65077. }
  65078. // Pointing Ray
  65079. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65080. if (!loadedMeshInfo.pointingPoseNode) {
  65081. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65082. }
  65083. return loadedMeshInfo;
  65084. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65085. function getChildByName(node, name) {
  65086. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65087. }
  65088. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65089. function getImmediateChildByName(node, name) {
  65090. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65091. }
  65092. };
  65093. WindowsMotionController.prototype.getForwardRay = function (length) {
  65094. if (length === void 0) { length = 100; }
  65095. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65096. return _super.prototype.getForwardRay.call(this, length);
  65097. }
  65098. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65099. var origin = m.getTranslation();
  65100. var forward = new BABYLON.Vector3(0, 0, -1);
  65101. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65102. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65103. return new BABYLON.Ray(origin, direction, length);
  65104. };
  65105. WindowsMotionController.prototype.dispose = function () {
  65106. _super.prototype.dispose.call(this);
  65107. this.onTrackpadChangedObservable.clear();
  65108. };
  65109. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65110. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65111. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65112. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65113. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65114. return WindowsMotionController;
  65115. }(BABYLON.WebVRController));
  65116. BABYLON.WindowsMotionController = WindowsMotionController;
  65117. })(BABYLON || (BABYLON = {}));
  65118. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65119. var BABYLON;
  65120. (function (BABYLON) {
  65121. var GearVRController = /** @class */ (function (_super) {
  65122. __extends(GearVRController, _super);
  65123. function GearVRController(vrGamepad) {
  65124. var _this = _super.call(this, vrGamepad) || this;
  65125. _this._buttonIndexToObservableNameMap = [
  65126. 'onTrackpadChangedObservable',
  65127. 'onTriggerStateChangedObservable' // Trigger
  65128. ];
  65129. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65130. return _this;
  65131. }
  65132. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65133. var _this = this;
  65134. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65135. _this._defaultModel = newMeshes[1];
  65136. _this.attachToMesh(_this._defaultModel);
  65137. if (meshLoaded) {
  65138. meshLoaded(_this._defaultModel);
  65139. }
  65140. });
  65141. };
  65142. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65143. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65144. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65145. // Only emit events for buttons that we know how to map from index to observable
  65146. var observable = this[observableName];
  65147. if (observable) {
  65148. observable.notifyObservers(state);
  65149. }
  65150. }
  65151. };
  65152. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65153. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65154. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65155. return GearVRController;
  65156. }(BABYLON.WebVRController));
  65157. BABYLON.GearVRController = GearVRController;
  65158. })(BABYLON || (BABYLON = {}));
  65159. //# sourceMappingURL=babylon.gearVRController.js.map
  65160. var BABYLON;
  65161. (function (BABYLON) {
  65162. /**
  65163. * Google Daydream controller
  65164. */
  65165. var DaydreamController = /** @class */ (function (_super) {
  65166. __extends(DaydreamController, _super);
  65167. function DaydreamController(vrGamepad) {
  65168. var _this = _super.call(this, vrGamepad) || this;
  65169. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65170. return _this;
  65171. }
  65172. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65173. var _this = this;
  65174. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65175. _this._defaultModel = newMeshes[1];
  65176. _this.attachToMesh(_this._defaultModel);
  65177. if (meshLoaded) {
  65178. meshLoaded(_this._defaultModel);
  65179. }
  65180. });
  65181. };
  65182. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65183. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65184. if (buttonIdx === 0) {
  65185. var observable = this.onTriggerStateChangedObservable;
  65186. if (observable) {
  65187. observable.notifyObservers(state);
  65188. }
  65189. }
  65190. else {
  65191. // If the app or home buttons are ever made available
  65192. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65193. }
  65194. };
  65195. /**
  65196. * Base Url for the controller model.
  65197. */
  65198. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65199. /**
  65200. * File name for the controller model.
  65201. */
  65202. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65203. /**
  65204. * Gamepad Id prefix used to identify Daydream Controller.
  65205. */
  65206. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65207. return DaydreamController;
  65208. }(BABYLON.WebVRController));
  65209. BABYLON.DaydreamController = DaydreamController;
  65210. })(BABYLON || (BABYLON = {}));
  65211. //# sourceMappingURL=babylon.daydreamController.js.map
  65212. var BABYLON;
  65213. (function (BABYLON) {
  65214. var FollowCamera = /** @class */ (function (_super) {
  65215. __extends(FollowCamera, _super);
  65216. function FollowCamera(name, position, scene, lockedTarget) {
  65217. if (lockedTarget === void 0) { lockedTarget = null; }
  65218. var _this = _super.call(this, name, position, scene) || this;
  65219. _this.radius = 12;
  65220. _this.rotationOffset = 0;
  65221. _this.heightOffset = 4;
  65222. _this.cameraAcceleration = 0.05;
  65223. _this.maxCameraSpeed = 20;
  65224. _this.lockedTarget = lockedTarget;
  65225. return _this;
  65226. }
  65227. FollowCamera.prototype.getRadians = function (degrees) {
  65228. return degrees * Math.PI / 180;
  65229. };
  65230. FollowCamera.prototype.follow = function (cameraTarget) {
  65231. if (!cameraTarget)
  65232. return;
  65233. var yRotation;
  65234. if (cameraTarget.rotationQuaternion) {
  65235. var rotMatrix = new BABYLON.Matrix();
  65236. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65237. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65238. }
  65239. else {
  65240. yRotation = cameraTarget.rotation.y;
  65241. }
  65242. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65243. var targetPosition = cameraTarget.getAbsolutePosition();
  65244. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65245. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65246. var dx = targetX - this.position.x;
  65247. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65248. var dz = (targetZ) - this.position.z;
  65249. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65250. var vy = dy * this.cameraAcceleration;
  65251. var vz = dz * this.cameraAcceleration * 2;
  65252. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65253. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65254. }
  65255. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65256. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65257. }
  65258. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65259. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65260. }
  65261. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65262. this.setTarget(targetPosition);
  65263. };
  65264. FollowCamera.prototype._checkInputs = function () {
  65265. _super.prototype._checkInputs.call(this);
  65266. if (this.lockedTarget) {
  65267. this.follow(this.lockedTarget);
  65268. }
  65269. };
  65270. FollowCamera.prototype.getClassName = function () {
  65271. return "FollowCamera";
  65272. };
  65273. __decorate([
  65274. BABYLON.serialize()
  65275. ], FollowCamera.prototype, "radius", void 0);
  65276. __decorate([
  65277. BABYLON.serialize()
  65278. ], FollowCamera.prototype, "rotationOffset", void 0);
  65279. __decorate([
  65280. BABYLON.serialize()
  65281. ], FollowCamera.prototype, "heightOffset", void 0);
  65282. __decorate([
  65283. BABYLON.serialize()
  65284. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65285. __decorate([
  65286. BABYLON.serialize()
  65287. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65288. __decorate([
  65289. BABYLON.serializeAsMeshReference("lockedTargetId")
  65290. ], FollowCamera.prototype, "lockedTarget", void 0);
  65291. return FollowCamera;
  65292. }(BABYLON.TargetCamera));
  65293. BABYLON.FollowCamera = FollowCamera;
  65294. var ArcFollowCamera = /** @class */ (function (_super) {
  65295. __extends(ArcFollowCamera, _super);
  65296. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65297. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65298. _this.alpha = alpha;
  65299. _this.beta = beta;
  65300. _this.radius = radius;
  65301. _this.target = target;
  65302. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65303. _this.follow();
  65304. return _this;
  65305. }
  65306. ArcFollowCamera.prototype.follow = function () {
  65307. if (!this.target) {
  65308. return;
  65309. }
  65310. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65311. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65312. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65313. var targetPosition = this.target.getAbsolutePosition();
  65314. this.position = targetPosition.add(this._cartesianCoordinates);
  65315. this.setTarget(targetPosition);
  65316. };
  65317. ArcFollowCamera.prototype._checkInputs = function () {
  65318. _super.prototype._checkInputs.call(this);
  65319. this.follow();
  65320. };
  65321. ArcFollowCamera.prototype.getClassName = function () {
  65322. return "ArcFollowCamera";
  65323. };
  65324. return ArcFollowCamera;
  65325. }(BABYLON.TargetCamera));
  65326. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65327. })(BABYLON || (BABYLON = {}));
  65328. //# sourceMappingURL=babylon.followCamera.js.map
  65329. var BABYLON;
  65330. (function (BABYLON) {
  65331. // We're mainly based on the logic defined into the FreeCamera code
  65332. var UniversalCamera = /** @class */ (function (_super) {
  65333. __extends(UniversalCamera, _super);
  65334. //-- end properties for backward compatibility for inputs
  65335. function UniversalCamera(name, position, scene) {
  65336. var _this = _super.call(this, name, position, scene) || this;
  65337. _this.inputs.addGamepad();
  65338. return _this;
  65339. }
  65340. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65341. //-- Begin properties for backward compatibility for inputs
  65342. get: function () {
  65343. var gamepad = this.inputs.attached["gamepad"];
  65344. if (gamepad)
  65345. return gamepad.gamepadAngularSensibility;
  65346. return 0;
  65347. },
  65348. set: function (value) {
  65349. var gamepad = this.inputs.attached["gamepad"];
  65350. if (gamepad)
  65351. gamepad.gamepadAngularSensibility = value;
  65352. },
  65353. enumerable: true,
  65354. configurable: true
  65355. });
  65356. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65357. get: function () {
  65358. var gamepad = this.inputs.attached["gamepad"];
  65359. if (gamepad)
  65360. return gamepad.gamepadMoveSensibility;
  65361. return 0;
  65362. },
  65363. set: function (value) {
  65364. var gamepad = this.inputs.attached["gamepad"];
  65365. if (gamepad)
  65366. gamepad.gamepadMoveSensibility = value;
  65367. },
  65368. enumerable: true,
  65369. configurable: true
  65370. });
  65371. UniversalCamera.prototype.getClassName = function () {
  65372. return "UniversalCamera";
  65373. };
  65374. return UniversalCamera;
  65375. }(BABYLON.TouchCamera));
  65376. BABYLON.UniversalCamera = UniversalCamera;
  65377. })(BABYLON || (BABYLON = {}));
  65378. //# sourceMappingURL=babylon.universalCamera.js.map
  65379. var BABYLON;
  65380. (function (BABYLON) {
  65381. // We're mainly based on the logic defined into the FreeCamera code
  65382. var GamepadCamera = /** @class */ (function (_super) {
  65383. __extends(GamepadCamera, _super);
  65384. //-- end properties for backward compatibility for inputs
  65385. function GamepadCamera(name, position, scene) {
  65386. return _super.call(this, name, position, scene) || this;
  65387. }
  65388. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65389. //-- Begin properties for backward compatibility for inputs
  65390. get: function () {
  65391. var gamepad = this.inputs.attached["gamepad"];
  65392. if (gamepad)
  65393. return gamepad.gamepadAngularSensibility;
  65394. return 0;
  65395. },
  65396. set: function (value) {
  65397. var gamepad = this.inputs.attached["gamepad"];
  65398. if (gamepad)
  65399. gamepad.gamepadAngularSensibility = value;
  65400. },
  65401. enumerable: true,
  65402. configurable: true
  65403. });
  65404. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65405. get: function () {
  65406. var gamepad = this.inputs.attached["gamepad"];
  65407. if (gamepad)
  65408. return gamepad.gamepadMoveSensibility;
  65409. return 0;
  65410. },
  65411. set: function (value) {
  65412. var gamepad = this.inputs.attached["gamepad"];
  65413. if (gamepad)
  65414. gamepad.gamepadMoveSensibility = value;
  65415. },
  65416. enumerable: true,
  65417. configurable: true
  65418. });
  65419. GamepadCamera.prototype.getClassName = function () {
  65420. return "GamepadCamera";
  65421. };
  65422. return GamepadCamera;
  65423. }(BABYLON.UniversalCamera));
  65424. BABYLON.GamepadCamera = GamepadCamera;
  65425. })(BABYLON || (BABYLON = {}));
  65426. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65427. var BABYLON;
  65428. (function (BABYLON) {
  65429. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65430. function PostProcessRenderPipelineManager() {
  65431. this._renderPipelines = {};
  65432. }
  65433. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65434. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65435. };
  65436. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65437. if (unique === void 0) { unique = false; }
  65438. var renderPipeline = this._renderPipelines[renderPipelineName];
  65439. if (!renderPipeline) {
  65440. return;
  65441. }
  65442. renderPipeline._attachCameras(cameras, unique);
  65443. };
  65444. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65445. var renderPipeline = this._renderPipelines[renderPipelineName];
  65446. if (!renderPipeline) {
  65447. return;
  65448. }
  65449. renderPipeline._detachCameras(cameras);
  65450. };
  65451. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65452. var renderPipeline = this._renderPipelines[renderPipelineName];
  65453. if (!renderPipeline) {
  65454. return;
  65455. }
  65456. renderPipeline._enableEffect(renderEffectName, cameras);
  65457. };
  65458. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65459. var renderPipeline = this._renderPipelines[renderPipelineName];
  65460. if (!renderPipeline) {
  65461. return;
  65462. }
  65463. renderPipeline._disableEffect(renderEffectName, cameras);
  65464. };
  65465. PostProcessRenderPipelineManager.prototype.update = function () {
  65466. for (var renderPipelineName in this._renderPipelines) {
  65467. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65468. var pipeline = this._renderPipelines[renderPipelineName];
  65469. if (!pipeline.isSupported) {
  65470. pipeline.dispose();
  65471. delete this._renderPipelines[renderPipelineName];
  65472. }
  65473. else {
  65474. pipeline._update();
  65475. }
  65476. }
  65477. }
  65478. };
  65479. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65480. for (var renderPipelineName in this._renderPipelines) {
  65481. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65482. var pipeline = this._renderPipelines[renderPipelineName];
  65483. pipeline._rebuild();
  65484. }
  65485. }
  65486. };
  65487. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65488. for (var renderPipelineName in this._renderPipelines) {
  65489. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65490. var pipeline = this._renderPipelines[renderPipelineName];
  65491. pipeline.dispose();
  65492. }
  65493. }
  65494. };
  65495. return PostProcessRenderPipelineManager;
  65496. }());
  65497. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65498. })(BABYLON || (BABYLON = {}));
  65499. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65500. var BABYLON;
  65501. (function (BABYLON) {
  65502. /**
  65503. * This represents a set of one or more post processes in Babylon.
  65504. * A post process can be used to apply a shader to a texture after it is rendered.
  65505. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65506. */
  65507. var PostProcessRenderEffect = /** @class */ (function () {
  65508. /**
  65509. * Instantiates a post process render effect.
  65510. * A post process can be used to apply a shader to a texture after it is rendered.
  65511. * @param engine The engine the effect is tied to
  65512. * @param name The name of the effect
  65513. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65514. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65515. */
  65516. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65517. this._name = name;
  65518. this._singleInstance = singleInstance || true;
  65519. this._getPostProcesses = getPostProcesses;
  65520. this._cameras = {};
  65521. this._indicesForCamera = {};
  65522. this._postProcesses = {};
  65523. }
  65524. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65525. /**
  65526. * Checks if all the post processes in the effect are supported.
  65527. */
  65528. get: function () {
  65529. for (var index in this._postProcesses) {
  65530. for (var ppIndex in this._postProcesses[index]) {
  65531. if (!this._postProcesses[index][ppIndex].isSupported) {
  65532. return false;
  65533. }
  65534. }
  65535. }
  65536. return true;
  65537. },
  65538. enumerable: true,
  65539. configurable: true
  65540. });
  65541. /**
  65542. * Updates the current state of the effect
  65543. */
  65544. PostProcessRenderEffect.prototype._update = function () {
  65545. };
  65546. /**
  65547. * Attaches the effect on cameras
  65548. * @param cameras The camera to attach to.
  65549. */
  65550. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65551. var _this = this;
  65552. var cameraKey;
  65553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65554. if (!cams) {
  65555. return;
  65556. }
  65557. for (var i = 0; i < cams.length; i++) {
  65558. var camera = cams[i];
  65559. var cameraName = camera.name;
  65560. if (this._singleInstance) {
  65561. cameraKey = 0;
  65562. }
  65563. else {
  65564. cameraKey = cameraName;
  65565. }
  65566. if (!this._postProcesses[cameraKey]) {
  65567. var postProcess = this._getPostProcesses();
  65568. if (postProcess) {
  65569. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65570. }
  65571. }
  65572. if (!this._indicesForCamera[cameraName]) {
  65573. this._indicesForCamera[cameraName] = [];
  65574. }
  65575. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65576. var index = camera.attachPostProcess(postProcess);
  65577. _this._indicesForCamera[cameraName].push(index);
  65578. });
  65579. if (!this._cameras[cameraName]) {
  65580. this._cameras[cameraName] = camera;
  65581. }
  65582. }
  65583. };
  65584. /**
  65585. * Detatches the effect on cameras
  65586. * @param cameras The camera to detatch from.
  65587. */
  65588. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65589. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65590. if (!cams) {
  65591. return;
  65592. }
  65593. for (var i = 0; i < cams.length; i++) {
  65594. var camera = cams[i];
  65595. var cameraName = camera.name;
  65596. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65597. camera.detachPostProcess(postProcess);
  65598. });
  65599. if (this._cameras[cameraName]) {
  65600. //this._indicesForCamera.splice(index, 1);
  65601. this._cameras[cameraName] = null;
  65602. }
  65603. }
  65604. };
  65605. /**
  65606. * Enables the effect on given cameras
  65607. * @param cameras The camera to enable.
  65608. */
  65609. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65610. var _this = this;
  65611. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65612. if (!cams) {
  65613. return;
  65614. }
  65615. for (var i = 0; i < cams.length; i++) {
  65616. var camera = cams[i];
  65617. var cameraName = camera.name;
  65618. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65619. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65620. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65621. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65622. });
  65623. }
  65624. }
  65625. }
  65626. };
  65627. /**
  65628. * Disables the effect on the given cameras
  65629. * @param cameras The camera to disable.
  65630. */
  65631. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65632. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65633. if (!cams) {
  65634. return;
  65635. }
  65636. for (var i = 0; i < cams.length; i++) {
  65637. var camera = cams[i];
  65638. var cameraName = camera.name;
  65639. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65640. camera.detachPostProcess(postProcess);
  65641. });
  65642. }
  65643. };
  65644. /**
  65645. * Gets a list of the post processes contained in the effect.
  65646. * @param camera The camera to get the post processes on.
  65647. * @returns The list of the post processes in the effect.
  65648. */
  65649. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65650. if (this._singleInstance) {
  65651. return this._postProcesses[0];
  65652. }
  65653. else {
  65654. if (!camera) {
  65655. return null;
  65656. }
  65657. return this._postProcesses[camera.name];
  65658. }
  65659. };
  65660. return PostProcessRenderEffect;
  65661. }());
  65662. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65663. })(BABYLON || (BABYLON = {}));
  65664. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65665. var BABYLON;
  65666. (function (BABYLON) {
  65667. var PostProcessRenderPipeline = /** @class */ (function () {
  65668. function PostProcessRenderPipeline(engine, name) {
  65669. this.engine = engine;
  65670. this._name = name;
  65671. this._renderEffects = {};
  65672. this._renderEffectsForIsolatedPass = new Array();
  65673. this._cameras = [];
  65674. }
  65675. PostProcessRenderPipeline.prototype.getClassName = function () {
  65676. return "PostProcessRenderPipeline";
  65677. };
  65678. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65679. get: function () {
  65680. for (var renderEffectName in this._renderEffects) {
  65681. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65682. if (!this._renderEffects[renderEffectName].isSupported) {
  65683. return false;
  65684. }
  65685. }
  65686. }
  65687. return true;
  65688. },
  65689. enumerable: true,
  65690. configurable: true
  65691. });
  65692. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65693. this._renderEffects[renderEffect._name] = renderEffect;
  65694. };
  65695. // private
  65696. PostProcessRenderPipeline.prototype._rebuild = function () {
  65697. };
  65698. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65699. var renderEffects = this._renderEffects[renderEffectName];
  65700. if (!renderEffects) {
  65701. return;
  65702. }
  65703. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65704. };
  65705. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65706. var renderEffects = this._renderEffects[renderEffectName];
  65707. if (!renderEffects) {
  65708. return;
  65709. }
  65710. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65711. };
  65712. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65713. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65714. if (!cams) {
  65715. return;
  65716. }
  65717. var indicesToDelete = [];
  65718. var i;
  65719. for (i = 0; i < cams.length; i++) {
  65720. var camera = cams[i];
  65721. var cameraName = camera.name;
  65722. if (this._cameras.indexOf(camera) === -1) {
  65723. this._cameras[cameraName] = camera;
  65724. }
  65725. else if (unique) {
  65726. indicesToDelete.push(i);
  65727. }
  65728. }
  65729. for (i = 0; i < indicesToDelete.length; i++) {
  65730. cameras.splice(indicesToDelete[i], 1);
  65731. }
  65732. for (var renderEffectName in this._renderEffects) {
  65733. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65734. this._renderEffects[renderEffectName]._attachCameras(cams);
  65735. }
  65736. }
  65737. };
  65738. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65739. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65740. if (!cams) {
  65741. return;
  65742. }
  65743. for (var renderEffectName in this._renderEffects) {
  65744. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65745. this._renderEffects[renderEffectName]._detachCameras(cams);
  65746. }
  65747. }
  65748. for (var i = 0; i < cams.length; i++) {
  65749. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65750. }
  65751. };
  65752. PostProcessRenderPipeline.prototype._update = function () {
  65753. for (var renderEffectName in this._renderEffects) {
  65754. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65755. this._renderEffects[renderEffectName]._update();
  65756. }
  65757. }
  65758. for (var i = 0; i < this._cameras.length; i++) {
  65759. var cameraName = this._cameras[i].name;
  65760. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65761. this._renderEffectsForIsolatedPass[cameraName]._update();
  65762. }
  65763. }
  65764. };
  65765. PostProcessRenderPipeline.prototype._reset = function () {
  65766. this._renderEffects = {};
  65767. this._renderEffectsForIsolatedPass = new Array();
  65768. };
  65769. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65770. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  65771. var effectKeys = Object.keys(this._renderEffects);
  65772. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65773. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65774. if (postProcesses) {
  65775. postProcesses[0].samples = 4;
  65776. return true;
  65777. }
  65778. }
  65779. return false;
  65780. };
  65781. PostProcessRenderPipeline.prototype.dispose = function () {
  65782. // Must be implemented by children
  65783. };
  65784. __decorate([
  65785. BABYLON.serialize()
  65786. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65787. return PostProcessRenderPipeline;
  65788. }());
  65789. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65790. })(BABYLON || (BABYLON = {}));
  65791. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65792. var BABYLON;
  65793. (function (BABYLON) {
  65794. /**
  65795. * This represents a depth renderer in Babylon.
  65796. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65797. */
  65798. var DepthRenderer = /** @class */ (function () {
  65799. /**
  65800. * Instantiates a depth renderer
  65801. * @param scene The scene the renderer belongs to
  65802. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65803. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65804. */
  65805. function DepthRenderer(scene, type, camera) {
  65806. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65807. if (camera === void 0) { camera = null; }
  65808. var _this = this;
  65809. this._scene = scene;
  65810. this._camera = camera;
  65811. var engine = scene.getEngine();
  65812. // Render target
  65813. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65814. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65815. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65816. this._depthMap.refreshRate = 1;
  65817. this._depthMap.renderParticles = false;
  65818. this._depthMap.renderList = null;
  65819. // Camera to get depth map from to support multiple concurrent cameras
  65820. this._depthMap.activeCamera = this._camera;
  65821. this._depthMap.ignoreCameraViewport = true;
  65822. this._depthMap.useCameraPostProcesses = false;
  65823. // set default depth value to 1.0 (far away)
  65824. this._depthMap.onClearObservable.add(function (engine) {
  65825. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65826. });
  65827. // Custom render function
  65828. var renderSubMesh = function (subMesh) {
  65829. var mesh = subMesh.getRenderingMesh();
  65830. var scene = _this._scene;
  65831. var engine = scene.getEngine();
  65832. var material = subMesh.getMaterial();
  65833. if (!material) {
  65834. return;
  65835. }
  65836. // Culling and reverse (right handed system)
  65837. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65838. // Managing instances
  65839. var batch = mesh._getInstancesRenderList(subMesh._id);
  65840. if (batch.mustReturn) {
  65841. return;
  65842. }
  65843. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65844. var camera = _this._camera || scene.activeCamera;
  65845. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65846. engine.enableEffect(_this._effect);
  65847. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65848. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65849. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65850. // Alpha test
  65851. if (material && material.needAlphaTesting()) {
  65852. var alphaTexture = material.getAlphaTestTexture();
  65853. if (alphaTexture) {
  65854. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65855. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65856. }
  65857. }
  65858. // Bones
  65859. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65860. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65861. }
  65862. // Draw
  65863. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65864. }
  65865. };
  65866. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65867. var index;
  65868. if (depthOnlySubMeshes.length) {
  65869. engine.setColorWrite(false);
  65870. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65871. renderSubMesh(depthOnlySubMeshes.data[index]);
  65872. }
  65873. engine.setColorWrite(true);
  65874. }
  65875. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65876. renderSubMesh(opaqueSubMeshes.data[index]);
  65877. }
  65878. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65879. renderSubMesh(alphaTestSubMeshes.data[index]);
  65880. }
  65881. };
  65882. }
  65883. /**
  65884. * Creates the depth rendering effect and checks if the effect is ready.
  65885. * @param subMesh The submesh to be used to render the depth map of
  65886. * @param useInstances If multiple world instances should be used
  65887. * @returns if the depth renderer is ready to render the depth map
  65888. */
  65889. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65890. var material = subMesh.getMaterial();
  65891. if (material.disableDepthWrite) {
  65892. return false;
  65893. }
  65894. var defines = [];
  65895. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65896. var mesh = subMesh.getMesh();
  65897. // Alpha test
  65898. if (material && material.needAlphaTesting()) {
  65899. defines.push("#define ALPHATEST");
  65900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65901. attribs.push(BABYLON.VertexBuffer.UVKind);
  65902. defines.push("#define UV1");
  65903. }
  65904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65905. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65906. defines.push("#define UV2");
  65907. }
  65908. }
  65909. // Bones
  65910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65913. if (mesh.numBoneInfluencers > 4) {
  65914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65916. }
  65917. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65918. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65919. }
  65920. else {
  65921. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65922. }
  65923. // Instances
  65924. if (useInstances) {
  65925. defines.push("#define INSTANCES");
  65926. attribs.push("world0");
  65927. attribs.push("world1");
  65928. attribs.push("world2");
  65929. attribs.push("world3");
  65930. }
  65931. // Get correct effect
  65932. var join = defines.join("\n");
  65933. if (this._cachedDefines !== join) {
  65934. this._cachedDefines = join;
  65935. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65936. }
  65937. return this._effect.isReady();
  65938. };
  65939. /**
  65940. * Gets the texture which the depth map will be written to.
  65941. * @returns The depth map texture
  65942. */
  65943. DepthRenderer.prototype.getDepthMap = function () {
  65944. return this._depthMap;
  65945. };
  65946. /**
  65947. * Disposes of the depth renderer.
  65948. */
  65949. DepthRenderer.prototype.dispose = function () {
  65950. this._depthMap.dispose();
  65951. };
  65952. return DepthRenderer;
  65953. }());
  65954. BABYLON.DepthRenderer = DepthRenderer;
  65955. })(BABYLON || (BABYLON = {}));
  65956. //# sourceMappingURL=babylon.depthRenderer.js.map
  65957. var BABYLON;
  65958. (function (BABYLON) {
  65959. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65960. __extends(SSAORenderingPipeline, _super);
  65961. /**
  65962. * @constructor
  65963. * @param {string} name - The rendering pipeline name
  65964. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65965. * @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 }
  65966. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65967. */
  65968. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65969. var _this = _super.call(this, scene.getEngine(), name) || this;
  65970. // Members
  65971. /**
  65972. * The PassPostProcess id in the pipeline that contains the original scene color
  65973. * @type {string}
  65974. */
  65975. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65976. /**
  65977. * The SSAO PostProcess id in the pipeline
  65978. * @type {string}
  65979. */
  65980. _this.SSAORenderEffect = "SSAORenderEffect";
  65981. /**
  65982. * The horizontal blur PostProcess id in the pipeline
  65983. * @type {string}
  65984. */
  65985. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65986. /**
  65987. * The vertical blur PostProcess id in the pipeline
  65988. * @type {string}
  65989. */
  65990. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65991. /**
  65992. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65993. * @type {string}
  65994. */
  65995. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65996. /**
  65997. * The output strength of the SSAO post-process. Default value is 1.0.
  65998. * @type {number}
  65999. */
  66000. _this.totalStrength = 1.0;
  66001. /**
  66002. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66003. * @type {number}
  66004. */
  66005. _this.radius = 0.0001;
  66006. /**
  66007. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66008. * Must not be equal to fallOff and superior to fallOff.
  66009. * Default value is 0.975
  66010. * @type {number}
  66011. */
  66012. _this.area = 0.0075;
  66013. /**
  66014. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66015. * Must not be equal to area and inferior to area.
  66016. * Default value is 0.0
  66017. * @type {number}
  66018. */
  66019. _this.fallOff = 0.000001;
  66020. /**
  66021. * The base color of the SSAO post-process
  66022. * The final result is "base + ssao" between [0, 1]
  66023. * @type {number}
  66024. */
  66025. _this.base = 0.5;
  66026. _this._firstUpdate = true;
  66027. _this._scene = scene;
  66028. // Set up assets
  66029. _this._createRandomTexture();
  66030. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66031. var ssaoRatio = ratio.ssaoRatio || ratio;
  66032. var combineRatio = ratio.combineRatio || ratio;
  66033. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66034. _this._createSSAOPostProcess(ssaoRatio);
  66035. _this._createBlurPostProcess(ssaoRatio);
  66036. _this._createSSAOCombinePostProcess(combineRatio);
  66037. // Set up pipeline
  66038. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66039. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66040. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66041. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66042. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66043. // Finish
  66044. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66045. if (cameras)
  66046. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66047. return _this;
  66048. }
  66049. // Public Methods
  66050. /**
  66051. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66052. */
  66053. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66054. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66055. for (var i = 0; i < this._scene.cameras.length; i++) {
  66056. var camera = this._scene.cameras[i];
  66057. this._originalColorPostProcess.dispose(camera);
  66058. this._ssaoPostProcess.dispose(camera);
  66059. this._blurHPostProcess.dispose(camera);
  66060. this._blurVPostProcess.dispose(camera);
  66061. this._ssaoCombinePostProcess.dispose(camera);
  66062. }
  66063. this._randomTexture.dispose();
  66064. if (disableDepthRender)
  66065. this._scene.disableDepthRenderer();
  66066. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66067. _super.prototype.dispose.call(this);
  66068. };
  66069. // Private Methods
  66070. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66071. var _this = this;
  66072. var size = 16;
  66073. 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);
  66074. 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);
  66075. this._blurHPostProcess.onActivateObservable.add(function () {
  66076. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66077. _this._blurHPostProcess.kernel = size * dw;
  66078. });
  66079. this._blurVPostProcess.onActivateObservable.add(function () {
  66080. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66081. _this._blurVPostProcess.kernel = size * dw;
  66082. });
  66083. };
  66084. SSAORenderingPipeline.prototype._rebuild = function () {
  66085. this._firstUpdate = true;
  66086. _super.prototype._rebuild.call(this);
  66087. };
  66088. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66089. var _this = this;
  66090. var numSamples = 16;
  66091. var sampleSphere = [
  66092. 0.5381, 0.1856, -0.4319,
  66093. 0.1379, 0.2486, 0.4430,
  66094. 0.3371, 0.5679, -0.0057,
  66095. -0.6999, -0.0451, -0.0019,
  66096. 0.0689, -0.1598, -0.8547,
  66097. 0.0560, 0.0069, -0.1843,
  66098. -0.0146, 0.1402, 0.0762,
  66099. 0.0100, -0.1924, -0.0344,
  66100. -0.3577, -0.5301, -0.4358,
  66101. -0.3169, 0.1063, 0.0158,
  66102. 0.0103, -0.5869, 0.0046,
  66103. -0.0897, -0.4940, 0.3287,
  66104. 0.7119, -0.0154, -0.0918,
  66105. -0.0533, 0.0596, -0.5411,
  66106. 0.0352, -0.0631, 0.5460,
  66107. -0.4776, 0.2847, -0.0271
  66108. ];
  66109. var samplesFactor = 1.0 / numSamples;
  66110. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66111. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66112. "area", "fallOff", "base", "range", "viewport"
  66113. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66114. this._ssaoPostProcess.onApply = function (effect) {
  66115. if (_this._firstUpdate) {
  66116. effect.setArray3("sampleSphere", sampleSphere);
  66117. effect.setFloat("samplesFactor", samplesFactor);
  66118. effect.setFloat("randTextureTiles", 4.0);
  66119. }
  66120. effect.setFloat("totalStrength", _this.totalStrength);
  66121. effect.setFloat("radius", _this.radius);
  66122. effect.setFloat("area", _this.area);
  66123. effect.setFloat("fallOff", _this.fallOff);
  66124. effect.setFloat("base", _this.base);
  66125. effect.setTexture("textureSampler", _this._depthTexture);
  66126. effect.setTexture("randomSampler", _this._randomTexture);
  66127. };
  66128. };
  66129. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66130. var _this = this;
  66131. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66132. this._ssaoCombinePostProcess.onApply = function (effect) {
  66133. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66134. };
  66135. };
  66136. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66137. var size = 512;
  66138. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66139. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66140. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66141. var context = this._randomTexture.getContext();
  66142. var rand = function (min, max) {
  66143. return Math.random() * (max - min) + min;
  66144. };
  66145. var randVector = BABYLON.Vector3.Zero();
  66146. for (var x = 0; x < size; x++) {
  66147. for (var y = 0; y < size; y++) {
  66148. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66149. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66150. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66151. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66152. context.fillRect(x, y, 1, 1);
  66153. }
  66154. }
  66155. this._randomTexture.update(false);
  66156. };
  66157. __decorate([
  66158. BABYLON.serialize()
  66159. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66160. __decorate([
  66161. BABYLON.serialize()
  66162. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66163. __decorate([
  66164. BABYLON.serialize()
  66165. ], SSAORenderingPipeline.prototype, "area", void 0);
  66166. __decorate([
  66167. BABYLON.serialize()
  66168. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66169. __decorate([
  66170. BABYLON.serialize()
  66171. ], SSAORenderingPipeline.prototype, "base", void 0);
  66172. return SSAORenderingPipeline;
  66173. }(BABYLON.PostProcessRenderPipeline));
  66174. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66175. })(BABYLON || (BABYLON = {}));
  66176. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66177. var BABYLON;
  66178. (function (BABYLON) {
  66179. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66180. __extends(SSAO2RenderingPipeline, _super);
  66181. /**
  66182. * @constructor
  66183. * @param {string} name - The rendering pipeline name
  66184. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66185. * @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 }
  66186. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66187. */
  66188. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66189. var _this = _super.call(this, scene.getEngine(), name) || this;
  66190. // Members
  66191. /**
  66192. * The PassPostProcess id in the pipeline that contains the original scene color
  66193. * @type {string}
  66194. */
  66195. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66196. /**
  66197. * The SSAO PostProcess id in the pipeline
  66198. * @type {string}
  66199. */
  66200. _this.SSAORenderEffect = "SSAORenderEffect";
  66201. /**
  66202. * The horizontal blur PostProcess id in the pipeline
  66203. * @type {string}
  66204. */
  66205. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66206. /**
  66207. * The vertical blur PostProcess id in the pipeline
  66208. * @type {string}
  66209. */
  66210. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66211. /**
  66212. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66213. * @type {string}
  66214. */
  66215. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66216. /**
  66217. * The output strength of the SSAO post-process. Default value is 1.0.
  66218. * @type {number}
  66219. */
  66220. _this.totalStrength = 1.0;
  66221. /**
  66222. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66223. * @type {number}
  66224. */
  66225. _this.maxZ = 100.0;
  66226. /**
  66227. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66228. * @type {number}
  66229. */
  66230. _this.minZAspect = 0.2;
  66231. /**
  66232. * Number of samples used for the SSAO calculations. Default value is 8
  66233. * @type {number}
  66234. */
  66235. _this._samples = 8;
  66236. /**
  66237. * Are we using bilateral blur ?
  66238. * @type {boolean}
  66239. */
  66240. _this._expensiveBlur = true;
  66241. /**
  66242. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66243. * @type {number}
  66244. */
  66245. _this.radius = 2.0;
  66246. /**
  66247. * The base color of the SSAO post-process
  66248. * The final result is "base + ssao" between [0, 1]
  66249. * @type {number}
  66250. */
  66251. _this.base = 0.1;
  66252. _this._firstUpdate = true;
  66253. _this._scene = scene;
  66254. if (!_this.isSupported) {
  66255. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66256. return _this;
  66257. }
  66258. var ssaoRatio = ratio.ssaoRatio || ratio;
  66259. var blurRatio = ratio.blurRatio || ratio;
  66260. // Set up assets
  66261. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66262. _this._createRandomTexture();
  66263. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66264. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66265. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66266. _this._createSSAOPostProcess(1.0);
  66267. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66268. _this._createSSAOCombinePostProcess(blurRatio);
  66269. // Set up pipeline
  66270. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66271. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66272. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66273. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66274. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66275. // Finish
  66276. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66277. if (cameras)
  66278. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66279. return _this;
  66280. }
  66281. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66282. get: function () {
  66283. return this._samples;
  66284. },
  66285. set: function (n) {
  66286. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66287. this._samples = n;
  66288. this._sampleSphere = this._generateHemisphere();
  66289. this._firstUpdate = true;
  66290. },
  66291. enumerable: true,
  66292. configurable: true
  66293. });
  66294. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66295. get: function () {
  66296. return this._expensiveBlur;
  66297. },
  66298. set: function (b) {
  66299. 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"]);
  66300. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66301. this._expensiveBlur = b;
  66302. this._firstUpdate = true;
  66303. },
  66304. enumerable: true,
  66305. configurable: true
  66306. });
  66307. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66308. /**
  66309. * Support test.
  66310. * @type {boolean}
  66311. */
  66312. get: function () {
  66313. var engine = BABYLON.Engine.LastCreatedEngine;
  66314. if (!engine) {
  66315. return false;
  66316. }
  66317. return engine.getCaps().drawBuffersExtension;
  66318. },
  66319. enumerable: true,
  66320. configurable: true
  66321. });
  66322. // Public Methods
  66323. /**
  66324. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66325. */
  66326. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66327. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66328. for (var i = 0; i < this._scene.cameras.length; i++) {
  66329. var camera = this._scene.cameras[i];
  66330. this._originalColorPostProcess.dispose(camera);
  66331. this._ssaoPostProcess.dispose(camera);
  66332. this._blurHPostProcess.dispose(camera);
  66333. this._blurVPostProcess.dispose(camera);
  66334. this._ssaoCombinePostProcess.dispose(camera);
  66335. }
  66336. this._randomTexture.dispose();
  66337. if (disableGeometryBufferRenderer)
  66338. this._scene.disableGeometryBufferRenderer();
  66339. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66340. _super.prototype.dispose.call(this);
  66341. };
  66342. // Private Methods
  66343. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66344. var _this = this;
  66345. this._samplerOffsets = [];
  66346. var expensive = this.expensiveBlur;
  66347. for (var i = -8; i < 8; i++) {
  66348. this._samplerOffsets.push(i * 2 + 0.5);
  66349. }
  66350. 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");
  66351. this._blurHPostProcess.onApply = function (effect) {
  66352. if (!_this._scene.activeCamera) {
  66353. return;
  66354. }
  66355. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66356. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66357. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66358. effect.setFloat("radius", _this.radius);
  66359. effect.setTexture("depthSampler", _this._depthTexture);
  66360. if (_this._firstUpdate) {
  66361. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66362. }
  66363. };
  66364. 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");
  66365. this._blurVPostProcess.onApply = function (effect) {
  66366. if (!_this._scene.activeCamera) {
  66367. return;
  66368. }
  66369. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66370. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66371. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66372. effect.setFloat("radius", _this.radius);
  66373. effect.setTexture("depthSampler", _this._depthTexture);
  66374. if (_this._firstUpdate) {
  66375. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66376. _this._firstUpdate = false;
  66377. }
  66378. };
  66379. };
  66380. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66381. this._firstUpdate = true;
  66382. _super.prototype._rebuild.call(this);
  66383. };
  66384. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66385. var numSamples = this.samples;
  66386. var result = [];
  66387. var vector, scale;
  66388. var rand = function (min, max) {
  66389. return Math.random() * (max - min) + min;
  66390. };
  66391. var i = 0;
  66392. while (i < numSamples) {
  66393. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66394. vector.normalize();
  66395. scale = i / numSamples;
  66396. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66397. vector.scaleInPlace(scale);
  66398. result.push(vector.x, vector.y, vector.z);
  66399. i++;
  66400. }
  66401. return result;
  66402. };
  66403. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66404. var _this = this;
  66405. var numSamples = this.samples;
  66406. this._sampleSphere = this._generateHemisphere();
  66407. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66408. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66409. "base", "range", "projection", "near", "far", "texelSize",
  66410. "xViewport", "yViewport", "maxZ", "minZAspect"
  66411. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66412. this._ssaoPostProcess.onApply = function (effect) {
  66413. if (_this._firstUpdate) {
  66414. effect.setArray3("sampleSphere", _this._sampleSphere);
  66415. effect.setFloat("randTextureTiles", 4.0);
  66416. }
  66417. if (!_this._scene.activeCamera) {
  66418. return;
  66419. }
  66420. effect.setFloat("samplesFactor", 1 / _this.samples);
  66421. effect.setFloat("totalStrength", _this.totalStrength);
  66422. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66423. effect.setFloat("radius", _this.radius);
  66424. effect.setFloat("maxZ", _this.maxZ);
  66425. effect.setFloat("minZAspect", _this.minZAspect);
  66426. effect.setFloat("base", _this.base);
  66427. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66428. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66429. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66430. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66431. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66432. effect.setTexture("textureSampler", _this._depthTexture);
  66433. effect.setTexture("normalSampler", _this._normalTexture);
  66434. effect.setTexture("randomSampler", _this._randomTexture);
  66435. };
  66436. };
  66437. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66438. var _this = this;
  66439. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66440. this._ssaoCombinePostProcess.onApply = function (effect) {
  66441. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66442. };
  66443. };
  66444. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66445. var size = 512;
  66446. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66447. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66448. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66449. var context = this._randomTexture.getContext();
  66450. var rand = function (min, max) {
  66451. return Math.random() * (max - min) + min;
  66452. };
  66453. var randVector = BABYLON.Vector3.Zero();
  66454. for (var x = 0; x < size; x++) {
  66455. for (var y = 0; y < size; y++) {
  66456. randVector.x = rand(0.0, 1.0);
  66457. randVector.y = rand(0.0, 1.0);
  66458. randVector.z = 0.0;
  66459. randVector.normalize();
  66460. randVector.scaleInPlace(255);
  66461. randVector.x = Math.floor(randVector.x);
  66462. randVector.y = Math.floor(randVector.y);
  66463. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66464. context.fillRect(x, y, 1, 1);
  66465. }
  66466. }
  66467. this._randomTexture.update(false);
  66468. };
  66469. __decorate([
  66470. BABYLON.serialize()
  66471. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66472. __decorate([
  66473. BABYLON.serialize()
  66474. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66475. __decorate([
  66476. BABYLON.serialize()
  66477. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66478. __decorate([
  66479. BABYLON.serialize("samples")
  66480. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66481. __decorate([
  66482. BABYLON.serialize("expensiveBlur")
  66483. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66484. __decorate([
  66485. BABYLON.serialize()
  66486. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66487. __decorate([
  66488. BABYLON.serialize()
  66489. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66490. return SSAO2RenderingPipeline;
  66491. }(BABYLON.PostProcessRenderPipeline));
  66492. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66493. })(BABYLON || (BABYLON = {}));
  66494. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66495. // BABYLON.JS Chromatic Aberration GLSL Shader
  66496. // Author: Olivier Guyot
  66497. // Separates very slightly R, G and B colors on the edges of the screen
  66498. // Inspired by Francois Tarlier & Martins Upitis
  66499. var BABYLON;
  66500. (function (BABYLON) {
  66501. var LensRenderingPipeline = /** @class */ (function (_super) {
  66502. __extends(LensRenderingPipeline, _super);
  66503. /**
  66504. * @constructor
  66505. *
  66506. * Effect parameters are as follow:
  66507. * {
  66508. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66509. * edge_blur: number; // from 0 to x (1 for realism)
  66510. * distortion: number; // from 0 to x (1 for realism)
  66511. * grain_amount: number; // from 0 to 1
  66512. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66513. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66514. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66515. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66516. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66517. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66518. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66519. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66520. * }
  66521. * Note: if an effect parameter is unset, effect is disabled
  66522. *
  66523. * @param {string} name - The rendering pipeline name
  66524. * @param {object} parameters - An object containing all parameters (see above)
  66525. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66526. * @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)
  66527. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66528. */
  66529. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66530. if (ratio === void 0) { ratio = 1.0; }
  66531. var _this = _super.call(this, scene.getEngine(), name) || this;
  66532. // Lens effects can be of the following:
  66533. // - chromatic aberration (slight shift of RGB colors)
  66534. // - blur on the edge of the lens
  66535. // - lens distortion
  66536. // - depth-of-field blur & highlights enhancing
  66537. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66538. // - grain effect (noise or custom texture)
  66539. // Two additional texture samplers are needed:
  66540. // - depth map (for depth-of-field)
  66541. // - grain texture
  66542. /**
  66543. * The chromatic aberration PostProcess id in the pipeline
  66544. * @type {string}
  66545. */
  66546. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66547. /**
  66548. * The highlights enhancing PostProcess id in the pipeline
  66549. * @type {string}
  66550. */
  66551. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66552. /**
  66553. * The depth-of-field PostProcess id in the pipeline
  66554. * @type {string}
  66555. */
  66556. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66557. _this._scene = scene;
  66558. // Fetch texture samplers
  66559. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66560. if (parameters.grain_texture) {
  66561. _this._grainTexture = parameters.grain_texture;
  66562. }
  66563. else {
  66564. _this._createGrainTexture();
  66565. }
  66566. // save parameters
  66567. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66568. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66569. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66570. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66571. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66572. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66573. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66574. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66575. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66576. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66577. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66578. // Create effects
  66579. _this._createChromaticAberrationPostProcess(ratio);
  66580. _this._createHighlightsPostProcess(ratio);
  66581. _this._createDepthOfFieldPostProcess(ratio / 4);
  66582. // Set up pipeline
  66583. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66584. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66585. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66586. if (_this._highlightsGain === -1) {
  66587. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66588. }
  66589. // Finish
  66590. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66591. if (cameras) {
  66592. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66593. }
  66594. return _this;
  66595. }
  66596. // public methods (self explanatory)
  66597. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66598. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66599. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66600. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66601. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66602. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66603. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66604. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66605. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66606. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66607. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66608. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66609. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66610. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66611. };
  66612. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66613. this._highlightsPostProcess.updateEffect();
  66614. };
  66615. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66616. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66617. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66618. this._highlightsGain = amount;
  66619. };
  66620. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66621. if (this._highlightsGain === -1) {
  66622. this._highlightsGain = 1.0;
  66623. }
  66624. this._highlightsThreshold = amount;
  66625. };
  66626. LensRenderingPipeline.prototype.disableHighlights = function () {
  66627. this._highlightsGain = -1;
  66628. };
  66629. /**
  66630. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66631. */
  66632. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66633. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66634. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66635. this._chromaticAberrationPostProcess = null;
  66636. this._highlightsPostProcess = null;
  66637. this._depthOfFieldPostProcess = null;
  66638. this._grainTexture.dispose();
  66639. if (disableDepthRender)
  66640. this._scene.disableDepthRenderer();
  66641. };
  66642. // colors shifting and distortion
  66643. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66644. var _this = this;
  66645. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66646. [], // samplers
  66647. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66648. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66649. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66650. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66651. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66652. };
  66653. };
  66654. // highlights enhancing
  66655. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66656. var _this = this;
  66657. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66658. [], // samplers
  66659. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66660. this._highlightsPostProcess.onApply = function (effect) {
  66661. effect.setFloat('gain', _this._highlightsGain);
  66662. effect.setFloat('threshold', _this._highlightsThreshold);
  66663. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66664. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66665. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66666. };
  66667. };
  66668. // colors shifting and distortion
  66669. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66670. var _this = this;
  66671. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66672. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66673. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66674. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66675. this._depthOfFieldPostProcess.onApply = function (effect) {
  66676. effect.setTexture("depthSampler", _this._depthTexture);
  66677. effect.setTexture("grainSampler", _this._grainTexture);
  66678. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66679. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66680. effect.setFloat('grain_amount', _this._grainAmount);
  66681. effect.setBool('blur_noise', _this._blurNoise);
  66682. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66683. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66684. effect.setFloat('distortion', _this._distortion);
  66685. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66686. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66687. effect.setFloat('aperture', _this._dofAperture);
  66688. effect.setFloat('darken', _this._dofDarken);
  66689. effect.setFloat('edge_blur', _this._edgeBlur);
  66690. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66691. if (_this._scene.activeCamera) {
  66692. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66693. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66694. }
  66695. };
  66696. };
  66697. // creates a black and white random noise texture, 512x512
  66698. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66699. var size = 512;
  66700. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66701. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66702. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66703. var context = this._grainTexture.getContext();
  66704. var rand = function (min, max) {
  66705. return Math.random() * (max - min) + min;
  66706. };
  66707. var value;
  66708. for (var x = 0; x < size; x++) {
  66709. for (var y = 0; y < size; y++) {
  66710. value = Math.floor(rand(0.42, 0.58) * 255);
  66711. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66712. context.fillRect(x, y, 1, 1);
  66713. }
  66714. }
  66715. this._grainTexture.update(false);
  66716. };
  66717. return LensRenderingPipeline;
  66718. }(BABYLON.PostProcessRenderPipeline));
  66719. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66720. })(BABYLON || (BABYLON = {}));
  66721. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66722. var BABYLON;
  66723. (function (BABYLON) {
  66724. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66725. __extends(StandardRenderingPipeline, _super);
  66726. /**
  66727. * @constructor
  66728. * @param {string} name - The rendering pipeline name
  66729. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66730. * @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)
  66731. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66732. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66733. */
  66734. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66735. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66736. var _this = _super.call(this, scene.getEngine(), name) || this;
  66737. _this.downSampleX4PostProcess = null;
  66738. _this.brightPassPostProcess = null;
  66739. _this.blurHPostProcesses = [];
  66740. _this.blurVPostProcesses = [];
  66741. _this.textureAdderPostProcess = null;
  66742. _this.volumetricLightPostProcess = null;
  66743. _this.volumetricLightSmoothXPostProcess = null;
  66744. _this.volumetricLightSmoothYPostProcess = null;
  66745. _this.volumetricLightMergePostProces = null;
  66746. _this.volumetricLightFinalPostProcess = null;
  66747. _this.luminancePostProcess = null;
  66748. _this.luminanceDownSamplePostProcesses = [];
  66749. _this.hdrPostProcess = null;
  66750. _this.textureAdderFinalPostProcess = null;
  66751. _this.lensFlareFinalPostProcess = null;
  66752. _this.hdrFinalPostProcess = null;
  66753. _this.lensFlarePostProcess = null;
  66754. _this.lensFlareComposePostProcess = null;
  66755. _this.motionBlurPostProcess = null;
  66756. _this.depthOfFieldPostProcess = null;
  66757. // Values
  66758. _this.brightThreshold = 1.0;
  66759. _this.blurWidth = 512.0;
  66760. _this.horizontalBlur = false;
  66761. _this.exposure = 1.0;
  66762. _this.lensTexture = null;
  66763. _this.volumetricLightCoefficient = 0.2;
  66764. _this.volumetricLightPower = 4.0;
  66765. _this.volumetricLightBlurScale = 64.0;
  66766. _this.sourceLight = null;
  66767. _this.hdrMinimumLuminance = 1.0;
  66768. _this.hdrDecreaseRate = 0.5;
  66769. _this.hdrIncreaseRate = 0.5;
  66770. _this.lensColorTexture = null;
  66771. _this.lensFlareStrength = 20.0;
  66772. _this.lensFlareGhostDispersal = 1.4;
  66773. _this.lensFlareHaloWidth = 0.7;
  66774. _this.lensFlareDistortionStrength = 16.0;
  66775. _this.lensStarTexture = null;
  66776. _this.lensFlareDirtTexture = null;
  66777. _this.depthOfFieldDistance = 10.0;
  66778. _this.depthOfFieldBlurWidth = 64.0;
  66779. _this.motionStrength = 1.0;
  66780. // IAnimatable
  66781. _this.animations = [];
  66782. _this._currentDepthOfFieldSource = null;
  66783. _this._hdrCurrentLuminance = 1.0;
  66784. // Getters and setters
  66785. _this._bloomEnabled = true;
  66786. _this._depthOfFieldEnabled = false;
  66787. _this._vlsEnabled = false;
  66788. _this._lensFlareEnabled = false;
  66789. _this._hdrEnabled = false;
  66790. _this._motionBlurEnabled = false;
  66791. _this._motionBlurSamples = 64.0;
  66792. _this._volumetricLightStepsCount = 50.0;
  66793. _this._cameras = cameras || [];
  66794. // Initialize
  66795. _this._scene = scene;
  66796. _this._basePostProcess = originalPostProcess;
  66797. _this._ratio = ratio;
  66798. // Misc
  66799. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66800. // Finish
  66801. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66802. _this._buildPipeline();
  66803. return _this;
  66804. }
  66805. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66806. get: function () {
  66807. return this._bloomEnabled;
  66808. },
  66809. set: function (enabled) {
  66810. if (this._bloomEnabled === enabled) {
  66811. return;
  66812. }
  66813. this._bloomEnabled = enabled;
  66814. this._buildPipeline();
  66815. },
  66816. enumerable: true,
  66817. configurable: true
  66818. });
  66819. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66820. get: function () {
  66821. return this._depthOfFieldEnabled;
  66822. },
  66823. set: function (enabled) {
  66824. if (this._depthOfFieldEnabled === enabled) {
  66825. return;
  66826. }
  66827. this._depthOfFieldEnabled = enabled;
  66828. this._buildPipeline();
  66829. },
  66830. enumerable: true,
  66831. configurable: true
  66832. });
  66833. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66834. get: function () {
  66835. return this._lensFlareEnabled;
  66836. },
  66837. set: function (enabled) {
  66838. if (this._lensFlareEnabled === enabled) {
  66839. return;
  66840. }
  66841. this._lensFlareEnabled = enabled;
  66842. this._buildPipeline();
  66843. },
  66844. enumerable: true,
  66845. configurable: true
  66846. });
  66847. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66848. get: function () {
  66849. return this._hdrEnabled;
  66850. },
  66851. set: function (enabled) {
  66852. if (this._hdrEnabled === enabled) {
  66853. return;
  66854. }
  66855. this._hdrEnabled = enabled;
  66856. this._buildPipeline();
  66857. },
  66858. enumerable: true,
  66859. configurable: true
  66860. });
  66861. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66862. get: function () {
  66863. return this._vlsEnabled;
  66864. },
  66865. set: function (enabled) {
  66866. if (this._vlsEnabled === enabled) {
  66867. return;
  66868. }
  66869. if (enabled) {
  66870. var geometry = this._scene.enableGeometryBufferRenderer();
  66871. if (!geometry) {
  66872. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66873. return;
  66874. }
  66875. }
  66876. this._vlsEnabled = enabled;
  66877. this._buildPipeline();
  66878. },
  66879. enumerable: true,
  66880. configurable: true
  66881. });
  66882. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66883. get: function () {
  66884. return this._motionBlurEnabled;
  66885. },
  66886. set: function (enabled) {
  66887. if (this._motionBlurEnabled === enabled) {
  66888. return;
  66889. }
  66890. this._motionBlurEnabled = enabled;
  66891. this._buildPipeline();
  66892. },
  66893. enumerable: true,
  66894. configurable: true
  66895. });
  66896. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66897. get: function () {
  66898. return this._volumetricLightStepsCount;
  66899. },
  66900. set: function (count) {
  66901. if (this.volumetricLightPostProcess) {
  66902. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66903. }
  66904. this._volumetricLightStepsCount = count;
  66905. },
  66906. enumerable: true,
  66907. configurable: true
  66908. });
  66909. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66910. get: function () {
  66911. return this._motionBlurSamples;
  66912. },
  66913. set: function (samples) {
  66914. if (this.motionBlurPostProcess) {
  66915. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66916. }
  66917. this._motionBlurSamples = samples;
  66918. },
  66919. enumerable: true,
  66920. configurable: true
  66921. });
  66922. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66923. var _this = this;
  66924. var ratio = this._ratio;
  66925. var scene = this._scene;
  66926. this._disposePostProcesses();
  66927. this._reset();
  66928. // Create pass post-process
  66929. if (!this._basePostProcess) {
  66930. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66931. this.originalPostProcess.onApply = function (effect) {
  66932. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66933. };
  66934. }
  66935. else {
  66936. this.originalPostProcess = this._basePostProcess;
  66937. }
  66938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66939. this._currentDepthOfFieldSource = this.originalPostProcess;
  66940. if (this._vlsEnabled) {
  66941. // Create volumetric light
  66942. this._createVolumetricLightPostProcess(scene, ratio);
  66943. // Create volumetric light final post-process
  66944. 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);
  66945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66946. }
  66947. if (this._bloomEnabled) {
  66948. // Create down sample X4 post-process
  66949. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66950. // Create bright pass post-process
  66951. this._createBrightPassPostProcess(scene, ratio / 2);
  66952. // Create gaussian blur post-processes (down sampling blurs)
  66953. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66954. // Create texture adder post-process
  66955. this._createTextureAdderPostProcess(scene, ratio);
  66956. // Create depth-of-field source post-process
  66957. 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);
  66958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66959. }
  66960. if (this._lensFlareEnabled) {
  66961. // Create lens flare post-process
  66962. this._createLensFlarePostProcess(scene, ratio);
  66963. // Create depth-of-field source post-process post lens-flare and disable it now
  66964. 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);
  66965. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66966. }
  66967. if (this._hdrEnabled) {
  66968. // Create luminance
  66969. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66970. // Create HDR
  66971. this._createHdrPostProcess(scene, ratio);
  66972. // Create depth-of-field source post-process post hdr and disable it now
  66973. 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);
  66974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66975. }
  66976. if (this._depthOfFieldEnabled) {
  66977. // Create gaussian blur used by depth-of-field
  66978. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66979. // Create depth-of-field post-process
  66980. this._createDepthOfFieldPostProcess(scene, ratio);
  66981. }
  66982. if (this._motionBlurEnabled) {
  66983. // Create motion blur post-process
  66984. this._createMotionBlurPostProcess(scene, ratio);
  66985. }
  66986. if (this._cameras !== null) {
  66987. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66988. }
  66989. };
  66990. // Down Sample X4 Post-Processs
  66991. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66992. var _this = this;
  66993. var downSampleX4Offsets = new Array(32);
  66994. 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);
  66995. this.downSampleX4PostProcess.onApply = function (effect) {
  66996. var id = 0;
  66997. var width = _this.downSampleX4PostProcess.width;
  66998. var height = _this.downSampleX4PostProcess.height;
  66999. for (var i = -2; i < 2; i++) {
  67000. for (var j = -2; j < 2; j++) {
  67001. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67002. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67003. id += 2;
  67004. }
  67005. }
  67006. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67007. };
  67008. // Add to pipeline
  67009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67010. };
  67011. // Brightpass Post-Process
  67012. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67013. var _this = this;
  67014. var brightOffsets = new Array(8);
  67015. 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);
  67016. this.brightPassPostProcess.onApply = function (effect) {
  67017. var sU = (1.0 / _this.brightPassPostProcess.width);
  67018. var sV = (1.0 / _this.brightPassPostProcess.height);
  67019. brightOffsets[0] = -0.5 * sU;
  67020. brightOffsets[1] = 0.5 * sV;
  67021. brightOffsets[2] = 0.5 * sU;
  67022. brightOffsets[3] = 0.5 * sV;
  67023. brightOffsets[4] = -0.5 * sU;
  67024. brightOffsets[5] = -0.5 * sV;
  67025. brightOffsets[6] = 0.5 * sU;
  67026. brightOffsets[7] = -0.5 * sV;
  67027. effect.setArray2("dsOffsets", brightOffsets);
  67028. effect.setFloat("brightThreshold", _this.brightThreshold);
  67029. };
  67030. // Add to pipeline
  67031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67032. };
  67033. // Create blur H&V post-processes
  67034. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67035. var _this = this;
  67036. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67037. var engine = scene.getEngine();
  67038. 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);
  67039. 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);
  67040. blurX.onActivateObservable.add(function () {
  67041. var dw = blurX.width / engine.getRenderWidth();
  67042. blurX.kernel = _this[blurWidthKey] * dw;
  67043. });
  67044. blurY.onActivateObservable.add(function () {
  67045. var dw = blurY.height / engine.getRenderHeight();
  67046. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67047. });
  67048. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67050. this.blurHPostProcesses.push(blurX);
  67051. this.blurVPostProcesses.push(blurY);
  67052. };
  67053. // Create texture adder post-process
  67054. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67055. var _this = this;
  67056. 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);
  67057. this.textureAdderPostProcess.onApply = function (effect) {
  67058. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67059. effect.setTexture("lensSampler", _this.lensTexture);
  67060. effect.setFloat("exposure", _this.exposure);
  67061. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67062. };
  67063. // Add to pipeline
  67064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67065. };
  67066. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67067. var _this = this;
  67068. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67069. geometryRenderer.enablePosition = true;
  67070. var geometry = geometryRenderer.getGBuffer();
  67071. // Base post-process
  67072. 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));
  67073. var depthValues = BABYLON.Vector2.Zero();
  67074. this.volumetricLightPostProcess.onApply = function (effect) {
  67075. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67076. var generator = _this.sourceLight.getShadowGenerator();
  67077. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67078. effect.setTexture("positionSampler", geometry.textures[2]);
  67079. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67080. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67081. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67082. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67083. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67084. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67085. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67086. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67087. effect.setVector2("depthValues", depthValues);
  67088. }
  67089. };
  67090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67091. // Smooth
  67092. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67093. // Merge
  67094. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67095. this.volumetricLightMergePostProces.onApply = function (effect) {
  67096. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67097. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67098. };
  67099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67100. };
  67101. // Create luminance
  67102. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67103. var _this = this;
  67104. // Create luminance
  67105. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67106. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67107. var offsets = [];
  67108. this.luminancePostProcess.onApply = function (effect) {
  67109. var sU = (1.0 / _this.luminancePostProcess.width);
  67110. var sV = (1.0 / _this.luminancePostProcess.height);
  67111. offsets[0] = -0.5 * sU;
  67112. offsets[1] = 0.5 * sV;
  67113. offsets[2] = 0.5 * sU;
  67114. offsets[3] = 0.5 * sV;
  67115. offsets[4] = -0.5 * sU;
  67116. offsets[5] = -0.5 * sV;
  67117. offsets[6] = 0.5 * sU;
  67118. offsets[7] = -0.5 * sV;
  67119. effect.setArray2("lumOffsets", offsets);
  67120. };
  67121. // Add to pipeline
  67122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67123. // Create down sample luminance
  67124. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67125. var size = Math.pow(3, i);
  67126. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67127. if (i === 0) {
  67128. defines += "#define FINAL_DOWN_SAMPLER";
  67129. }
  67130. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67131. this.luminanceDownSamplePostProcesses.push(postProcess);
  67132. }
  67133. // Create callbacks and add effects
  67134. var lastLuminance = this.luminancePostProcess;
  67135. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67136. var downSampleOffsets = new Array(18);
  67137. pp.onApply = function (effect) {
  67138. if (!lastLuminance) {
  67139. return;
  67140. }
  67141. var id = 0;
  67142. for (var x = -1; x < 2; x++) {
  67143. for (var y = -1; y < 2; y++) {
  67144. downSampleOffsets[id] = x / lastLuminance.width;
  67145. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67146. id += 2;
  67147. }
  67148. }
  67149. effect.setArray2("dsOffsets", downSampleOffsets);
  67150. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67151. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67152. lastLuminance = _this.luminancePostProcess;
  67153. }
  67154. else {
  67155. lastLuminance = pp;
  67156. }
  67157. };
  67158. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67159. pp.onAfterRender = function (effect) {
  67160. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67161. 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);
  67162. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67163. };
  67164. }
  67165. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67166. });
  67167. };
  67168. // Create HDR post-process
  67169. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67170. var _this = this;
  67171. 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);
  67172. var outputLiminance = 1;
  67173. var time = 0;
  67174. var lastTime = 0;
  67175. this.hdrPostProcess.onApply = function (effect) {
  67176. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67177. time += scene.getEngine().getDeltaTime();
  67178. if (outputLiminance < 0) {
  67179. outputLiminance = _this._hdrCurrentLuminance;
  67180. }
  67181. else {
  67182. var dt = (lastTime - time) / 1000.0;
  67183. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67184. outputLiminance += _this.hdrDecreaseRate * dt;
  67185. }
  67186. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67187. outputLiminance -= _this.hdrIncreaseRate * dt;
  67188. }
  67189. else {
  67190. outputLiminance = _this._hdrCurrentLuminance;
  67191. }
  67192. }
  67193. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67194. effect.setFloat("averageLuminance", outputLiminance);
  67195. lastTime = time;
  67196. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67197. };
  67198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67199. };
  67200. // Create lens flare post-process
  67201. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67202. var _this = this;
  67203. 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);
  67204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67205. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67206. 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);
  67207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67208. var resolution = new BABYLON.Vector2(0, 0);
  67209. // Lens flare
  67210. this.lensFlarePostProcess.onApply = function (effect) {
  67211. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67212. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67213. effect.setFloat("strength", _this.lensFlareStrength);
  67214. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67215. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67216. // Shift
  67217. resolution.x = _this.lensFlarePostProcess.width;
  67218. resolution.y = _this.lensFlarePostProcess.height;
  67219. effect.setVector2("resolution", resolution);
  67220. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67221. };
  67222. // Compose
  67223. 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);
  67224. 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);
  67225. this.lensFlareComposePostProcess.onApply = function (effect) {
  67226. if (!_this._scene.activeCamera) {
  67227. return;
  67228. }
  67229. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67230. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67231. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67232. // Lens start rotation matrix
  67233. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67234. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67235. 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));
  67236. camRot *= 4.0;
  67237. 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);
  67238. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67239. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67240. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67241. };
  67242. };
  67243. // Create depth-of-field post-process
  67244. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67245. var _this = this;
  67246. 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);
  67247. this.depthOfFieldPostProcess.onApply = function (effect) {
  67248. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67249. effect.setTexture("depthSampler", _this._getDepthTexture());
  67250. effect.setFloat("distance", _this.depthOfFieldDistance);
  67251. };
  67252. // Add to pipeline
  67253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67254. };
  67255. // Create motion blur post-process
  67256. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67257. var _this = this;
  67258. 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);
  67259. var motionScale = 0;
  67260. var prevViewProjection = BABYLON.Matrix.Identity();
  67261. var invViewProjection = BABYLON.Matrix.Identity();
  67262. var viewProjection = BABYLON.Matrix.Identity();
  67263. var screenSize = BABYLON.Vector2.Zero();
  67264. this.motionBlurPostProcess.onApply = function (effect) {
  67265. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67266. viewProjection.invertToRef(invViewProjection);
  67267. effect.setMatrix("inverseViewProjection", invViewProjection);
  67268. effect.setMatrix("prevViewProjection", prevViewProjection);
  67269. prevViewProjection = viewProjection;
  67270. screenSize.x = _this.motionBlurPostProcess.width;
  67271. screenSize.y = _this.motionBlurPostProcess.height;
  67272. effect.setVector2("screenSize", screenSize);
  67273. motionScale = scene.getEngine().getFps() / 60.0;
  67274. effect.setFloat("motionScale", motionScale);
  67275. effect.setFloat("motionStrength", _this.motionStrength);
  67276. effect.setTexture("depthSampler", _this._getDepthTexture());
  67277. };
  67278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67279. };
  67280. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67281. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67282. var renderer = this._scene.enableGeometryBufferRenderer();
  67283. return renderer.getGBuffer().textures[0];
  67284. }
  67285. return this._scene.enableDepthRenderer().getDepthMap();
  67286. };
  67287. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67288. for (var i = 0; i < this._cameras.length; i++) {
  67289. var camera = this._cameras[i];
  67290. if (this.originalPostProcess) {
  67291. this.originalPostProcess.dispose(camera);
  67292. }
  67293. if (this.downSampleX4PostProcess) {
  67294. this.downSampleX4PostProcess.dispose(camera);
  67295. }
  67296. if (this.brightPassPostProcess) {
  67297. this.brightPassPostProcess.dispose(camera);
  67298. }
  67299. if (this.textureAdderPostProcess) {
  67300. this.textureAdderPostProcess.dispose(camera);
  67301. }
  67302. if (this.textureAdderFinalPostProcess) {
  67303. this.textureAdderFinalPostProcess.dispose(camera);
  67304. }
  67305. if (this.volumetricLightPostProcess) {
  67306. this.volumetricLightPostProcess.dispose(camera);
  67307. }
  67308. if (this.volumetricLightSmoothXPostProcess) {
  67309. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67310. }
  67311. if (this.volumetricLightSmoothYPostProcess) {
  67312. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67313. }
  67314. if (this.volumetricLightMergePostProces) {
  67315. this.volumetricLightMergePostProces.dispose(camera);
  67316. }
  67317. if (this.volumetricLightFinalPostProcess) {
  67318. this.volumetricLightFinalPostProcess.dispose(camera);
  67319. }
  67320. if (this.lensFlarePostProcess) {
  67321. this.lensFlarePostProcess.dispose(camera);
  67322. }
  67323. if (this.lensFlareComposePostProcess) {
  67324. this.lensFlareComposePostProcess.dispose(camera);
  67325. }
  67326. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67327. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67328. }
  67329. if (this.luminancePostProcess) {
  67330. this.luminancePostProcess.dispose(camera);
  67331. }
  67332. if (this.hdrPostProcess) {
  67333. this.hdrPostProcess.dispose(camera);
  67334. }
  67335. if (this.hdrFinalPostProcess) {
  67336. this.hdrFinalPostProcess.dispose(camera);
  67337. }
  67338. if (this.depthOfFieldPostProcess) {
  67339. this.depthOfFieldPostProcess.dispose(camera);
  67340. }
  67341. if (this.motionBlurPostProcess) {
  67342. this.motionBlurPostProcess.dispose(camera);
  67343. }
  67344. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67345. this.blurHPostProcesses[j].dispose(camera);
  67346. }
  67347. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67348. this.blurVPostProcesses[j].dispose(camera);
  67349. }
  67350. }
  67351. this.originalPostProcess = null;
  67352. this.downSampleX4PostProcess = null;
  67353. this.brightPassPostProcess = null;
  67354. this.textureAdderPostProcess = null;
  67355. this.textureAdderFinalPostProcess = null;
  67356. this.volumetricLightPostProcess = null;
  67357. this.volumetricLightSmoothXPostProcess = null;
  67358. this.volumetricLightSmoothYPostProcess = null;
  67359. this.volumetricLightMergePostProces = null;
  67360. this.volumetricLightFinalPostProcess = null;
  67361. this.lensFlarePostProcess = null;
  67362. this.lensFlareComposePostProcess = null;
  67363. this.luminancePostProcess = null;
  67364. this.hdrPostProcess = null;
  67365. this.hdrFinalPostProcess = null;
  67366. this.depthOfFieldPostProcess = null;
  67367. this.motionBlurPostProcess = null;
  67368. this.luminanceDownSamplePostProcesses = [];
  67369. this.blurHPostProcesses = [];
  67370. this.blurVPostProcesses = [];
  67371. };
  67372. // Dispose
  67373. StandardRenderingPipeline.prototype.dispose = function () {
  67374. this._disposePostProcesses();
  67375. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67376. _super.prototype.dispose.call(this);
  67377. };
  67378. // Serialize rendering pipeline
  67379. StandardRenderingPipeline.prototype.serialize = function () {
  67380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67381. serializationObject.customType = "StandardRenderingPipeline";
  67382. return serializationObject;
  67383. };
  67384. /**
  67385. * Static members
  67386. */
  67387. // Parse serialized pipeline
  67388. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67389. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67390. };
  67391. // Luminance steps
  67392. StandardRenderingPipeline.LuminanceSteps = 6;
  67393. __decorate([
  67394. BABYLON.serialize()
  67395. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67396. __decorate([
  67397. BABYLON.serialize()
  67398. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67399. __decorate([
  67400. BABYLON.serialize()
  67401. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67402. __decorate([
  67403. BABYLON.serialize()
  67404. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67405. __decorate([
  67406. BABYLON.serializeAsTexture("lensTexture")
  67407. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67408. __decorate([
  67409. BABYLON.serialize()
  67410. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67411. __decorate([
  67412. BABYLON.serialize()
  67413. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67414. __decorate([
  67415. BABYLON.serialize()
  67416. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67417. __decorate([
  67418. BABYLON.serialize()
  67419. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67420. __decorate([
  67421. BABYLON.serialize()
  67422. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67423. __decorate([
  67424. BABYLON.serialize()
  67425. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67426. __decorate([
  67427. BABYLON.serializeAsTexture("lensColorTexture")
  67428. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67429. __decorate([
  67430. BABYLON.serialize()
  67431. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67432. __decorate([
  67433. BABYLON.serialize()
  67434. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67435. __decorate([
  67436. BABYLON.serialize()
  67437. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67438. __decorate([
  67439. BABYLON.serialize()
  67440. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67441. __decorate([
  67442. BABYLON.serializeAsTexture("lensStarTexture")
  67443. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67444. __decorate([
  67445. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67446. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67447. __decorate([
  67448. BABYLON.serialize()
  67449. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67450. __decorate([
  67451. BABYLON.serialize()
  67452. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67453. __decorate([
  67454. BABYLON.serialize()
  67455. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67456. __decorate([
  67457. BABYLON.serialize()
  67458. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67459. __decorate([
  67460. BABYLON.serialize()
  67461. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67462. __decorate([
  67463. BABYLON.serialize()
  67464. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67465. __decorate([
  67466. BABYLON.serialize()
  67467. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67468. __decorate([
  67469. BABYLON.serialize()
  67470. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67471. __decorate([
  67472. BABYLON.serialize()
  67473. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67474. __decorate([
  67475. BABYLON.serialize()
  67476. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67477. __decorate([
  67478. BABYLON.serialize()
  67479. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67480. __decorate([
  67481. BABYLON.serialize()
  67482. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67483. return StandardRenderingPipeline;
  67484. }(BABYLON.PostProcessRenderPipeline));
  67485. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67486. })(BABYLON || (BABYLON = {}));
  67487. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67488. var BABYLON;
  67489. (function (BABYLON) {
  67490. var FxaaPostProcess = /** @class */ (function (_super) {
  67491. __extends(FxaaPostProcess, _super);
  67492. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67493. if (camera === void 0) { camera = null; }
  67494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67495. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67496. _this.onApplyObservable.add(function (effect) {
  67497. var texelSize = _this.texelSize;
  67498. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67499. });
  67500. return _this;
  67501. }
  67502. return FxaaPostProcess;
  67503. }(BABYLON.PostProcess));
  67504. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67505. })(BABYLON || (BABYLON = {}));
  67506. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67507. var BABYLON;
  67508. (function (BABYLON) {
  67509. /**
  67510. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67511. */
  67512. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67513. __extends(CircleOfConfusionPostProcess, _super);
  67514. /**
  67515. * Creates a new instance of @see CircleOfConfusionPostProcess
  67516. * @param name The name of the effect.
  67517. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67518. * @param options The required width/height ratio to downsize to before computing the render pass.
  67519. * @param camera The camera to apply the render pass to.
  67520. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67521. * @param engine The engine which the post process will be applied. (default: current engine)
  67522. * @param reusable If the post process can be reused on the same frame. (default: false)
  67523. * @param textureType Type of textures used when performing the post process. (default: 0)
  67524. */
  67525. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67526. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67527. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67528. /**
  67529. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  67530. */
  67531. _this.lensSize = 50;
  67532. /**
  67533. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67534. */
  67535. _this.fStop = 1.4;
  67536. /**
  67537. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67538. */
  67539. _this.focusDistance = 2000;
  67540. /**
  67541. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67542. */
  67543. _this.focalLength = 50;
  67544. _this.onApplyObservable.add(function (effect) {
  67545. effect.setTexture("depthSampler", depthTexture);
  67546. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67547. var aperture = _this.lensSize / _this.fStop;
  67548. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67549. effect.setFloat('focusDistance', _this.focusDistance);
  67550. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67551. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67552. });
  67553. return _this;
  67554. }
  67555. return CircleOfConfusionPostProcess;
  67556. }(BABYLON.PostProcess));
  67557. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67558. })(BABYLON || (BABYLON = {}));
  67559. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67560. var BABYLON;
  67561. (function (BABYLON) {
  67562. /**
  67563. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67564. */
  67565. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67566. __extends(DepthOfFieldMergePostProcess, _super);
  67567. /**
  67568. * Creates a new instance of @see CircleOfConfusionPostProcess
  67569. * @param name The name of the effect.
  67570. * @param original The non-blurred image to be modified
  67571. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67572. * @param blurSteps Incrimental bluring post processes.
  67573. * @param options The required width/height ratio to downsize to before computing the render pass.
  67574. * @param camera The camera to apply the render pass to.
  67575. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67576. * @param engine The engine which the post process will be applied. (default: current engine)
  67577. * @param reusable If the post process can be reused on the same frame. (default: false)
  67578. * @param textureType Type of textures used when performing the post process. (default: 0)
  67579. */
  67580. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67582. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67583. _this.onApplyObservable.add(function (effect) {
  67584. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67585. effect.setTextureFromPostProcess("originalSampler", original);
  67586. blurSteps.forEach(function (step, index) {
  67587. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67588. });
  67589. });
  67590. return _this;
  67591. }
  67592. return DepthOfFieldMergePostProcess;
  67593. }(BABYLON.PostProcess));
  67594. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67595. })(BABYLON || (BABYLON = {}));
  67596. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67597. var BABYLON;
  67598. (function (BABYLON) {
  67599. /**
  67600. * Specifies the level of max blur that should be applied when using the depth of field effect
  67601. */
  67602. var DepthOfFieldEffectBlurLevel;
  67603. (function (DepthOfFieldEffectBlurLevel) {
  67604. /**
  67605. * Subtle blur
  67606. */
  67607. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67608. /**
  67609. * Medium blur
  67610. */
  67611. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67612. /**
  67613. * Large blur
  67614. */
  67615. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67616. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67617. ;
  67618. /**
  67619. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67620. */
  67621. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67622. __extends(DepthOfFieldEffect, _super);
  67623. /**
  67624. * Creates a new instance of @see DepthOfFieldEffect
  67625. * @param scene The scene the effect belongs to.
  67626. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67627. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67628. */
  67629. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67630. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67631. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67632. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67633. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67634. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67635. // Capture circle of confusion texture
  67636. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67637. _this._depthOfFieldPass.autoClear = false;
  67638. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  67639. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67640. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67641. _this._depthOfFieldBlurY = [];
  67642. _this._depthOfFieldBlurX = [];
  67643. var blurCount = 1;
  67644. var kernelSize = 15;
  67645. switch (blurLevel) {
  67646. case DepthOfFieldEffectBlurLevel.High: {
  67647. blurCount = 3;
  67648. kernelSize = 51;
  67649. break;
  67650. }
  67651. case DepthOfFieldEffectBlurLevel.Medium: {
  67652. blurCount = 2;
  67653. kernelSize = 31;
  67654. break;
  67655. }
  67656. default: {
  67657. kernelSize = 15;
  67658. blurCount = 1;
  67659. break;
  67660. }
  67661. }
  67662. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67663. for (var i = 0; i < blurCount; i++) {
  67664. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67665. blurY.autoClear = false;
  67666. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67667. blurX.autoClear = false;
  67668. _this._depthOfFieldBlurY.push(blurY);
  67669. _this._depthOfFieldBlurX.push(blurX);
  67670. }
  67671. // Merge blurred images with original image based on circleOfConfusion
  67672. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67673. _this._depthOfFieldMerge.autoClear = false;
  67674. // Set all post processes on the effect.
  67675. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67676. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67677. effects.push(_this._depthOfFieldBlurY[i]);
  67678. effects.push(_this._depthOfFieldBlurX[i]);
  67679. }
  67680. effects.push(_this._depthOfFieldMerge);
  67681. return effects;
  67682. }, true) || this;
  67683. return _this;
  67684. }
  67685. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67686. get: function () {
  67687. return this._circleOfConfusion.focalLength;
  67688. },
  67689. /**
  67690. * The focal the length of the camera used in the effect
  67691. */
  67692. set: function (value) {
  67693. this._circleOfConfusion.focalLength = value;
  67694. },
  67695. enumerable: true,
  67696. configurable: true
  67697. });
  67698. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67699. get: function () {
  67700. return this._circleOfConfusion.fStop;
  67701. },
  67702. /**
  67703. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67704. */
  67705. set: function (value) {
  67706. this._circleOfConfusion.fStop = value;
  67707. },
  67708. enumerable: true,
  67709. configurable: true
  67710. });
  67711. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67712. get: function () {
  67713. return this._circleOfConfusion.focusDistance;
  67714. },
  67715. /**
  67716. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67717. */
  67718. set: function (value) {
  67719. this._circleOfConfusion.focusDistance = value;
  67720. },
  67721. enumerable: true,
  67722. configurable: true
  67723. });
  67724. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67725. get: function () {
  67726. return this._circleOfConfusion.lensSize;
  67727. },
  67728. /**
  67729. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  67730. */
  67731. set: function (value) {
  67732. this._circleOfConfusion.lensSize = value;
  67733. },
  67734. enumerable: true,
  67735. configurable: true
  67736. });
  67737. /**
  67738. * Disposes each of the internal effects for a given camera.
  67739. * @param camera The camera to dispose the effect on.
  67740. */
  67741. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67742. this._depthOfFieldPass.dispose(camera);
  67743. this._circleOfConfusion.dispose(camera);
  67744. this._depthOfFieldBlurX.forEach(function (element) {
  67745. element.dispose(camera);
  67746. });
  67747. this._depthOfFieldBlurY.forEach(function (element) {
  67748. element.dispose(camera);
  67749. });
  67750. this._depthOfFieldMerge.dispose(camera);
  67751. };
  67752. return DepthOfFieldEffect;
  67753. }(BABYLON.PostProcessRenderEffect));
  67754. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67755. })(BABYLON || (BABYLON = {}));
  67756. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67757. var BABYLON;
  67758. (function (BABYLON) {
  67759. /**
  67760. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67761. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67762. */
  67763. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67764. __extends(DefaultRenderingPipeline, _super);
  67765. /**
  67766. * @constructor
  67767. * @param {string} name - The rendering pipeline name
  67768. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67769. * @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)
  67770. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67771. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67772. */
  67773. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67774. if (automaticBuild === void 0) { automaticBuild = true; }
  67775. var _this = _super.call(this, scene.getEngine(), name) || this;
  67776. /**
  67777. * ID of the sharpen post process,
  67778. */
  67779. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67780. /**
  67781. * ID of the pass post process used for bloom,
  67782. */
  67783. _this.PassPostProcessId = "PassPostProcessEffect";
  67784. /**
  67785. * ID of the highlight post process used for bloom,
  67786. */
  67787. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67788. /**
  67789. * ID of the blurX post process used for bloom,
  67790. */
  67791. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67792. /**
  67793. * ID of the blurY post process used for bloom,
  67794. */
  67795. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67796. /**
  67797. * ID of the copy back post process used for bloom,
  67798. */
  67799. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67800. /**
  67801. * ID of the image processing post process;
  67802. */
  67803. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67804. /**
  67805. * ID of the Fast Approximate Anti-Aliasing post process;
  67806. */
  67807. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67808. /**
  67809. * ID of the final merge post process;
  67810. */
  67811. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67812. /**
  67813. * Animations which can be used to tweak settings over a period of time
  67814. */
  67815. _this.animations = [];
  67816. // Values
  67817. _this._sharpenEnabled = false;
  67818. _this._bloomEnabled = false;
  67819. _this._depthOfFieldEnabled = false;
  67820. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67821. _this._fxaaEnabled = false;
  67822. _this._msaaEnabled = false;
  67823. _this._imageProcessingEnabled = true;
  67824. _this._bloomScale = 0.6;
  67825. _this._buildAllowed = true;
  67826. /**
  67827. * Specifies the size of the bloom blur kernel, relative to the final output size
  67828. */
  67829. _this.bloomKernel = 64;
  67830. /**
  67831. * Specifies the weight of the bloom in the final rendering
  67832. */
  67833. _this._bloomWeight = 0.15;
  67834. _this._cameras = cameras || [];
  67835. _this._buildAllowed = automaticBuild;
  67836. // Initialize
  67837. _this._scene = scene;
  67838. var caps = _this._scene.getEngine().getCaps();
  67839. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67840. // Misc
  67841. if (_this._hdr) {
  67842. if (caps.textureHalfFloatRender) {
  67843. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67844. }
  67845. else if (caps.textureFloatRender) {
  67846. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67847. }
  67848. }
  67849. else {
  67850. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67851. }
  67852. // Attach
  67853. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67854. _this._buildPipeline();
  67855. return _this;
  67856. }
  67857. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  67858. get: function () {
  67859. return this._sharpenEnabled;
  67860. },
  67861. /**
  67862. * Enable or disable the sharpen process from the pipeline
  67863. */
  67864. set: function (enabled) {
  67865. if (this._sharpenEnabled === enabled) {
  67866. return;
  67867. }
  67868. this._sharpenEnabled = enabled;
  67869. this._buildPipeline();
  67870. },
  67871. enumerable: true,
  67872. configurable: true
  67873. });
  67874. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67875. get: function () {
  67876. return this._bloomWeight;
  67877. },
  67878. /**
  67879. * The strength of the bloom.
  67880. */
  67881. set: function (value) {
  67882. if (this._bloomWeight === value) {
  67883. return;
  67884. }
  67885. this._bloomWeight = value;
  67886. if (this._hdr && this.copyBack) {
  67887. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67888. }
  67889. },
  67890. enumerable: true,
  67891. configurable: true
  67892. });
  67893. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67894. get: function () {
  67895. return this._bloomScale;
  67896. },
  67897. /**
  67898. * The scale of the bloom, lower value will provide better performance.
  67899. */
  67900. set: function (value) {
  67901. if (this._bloomScale === value) {
  67902. return;
  67903. }
  67904. this._bloomScale = value;
  67905. this._buildPipeline();
  67906. },
  67907. enumerable: true,
  67908. configurable: true
  67909. });
  67910. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67911. get: function () {
  67912. return this._bloomEnabled;
  67913. },
  67914. /**
  67915. * Enable or disable the bloom from the pipeline
  67916. */
  67917. set: function (enabled) {
  67918. if (this._bloomEnabled === enabled) {
  67919. return;
  67920. }
  67921. this._bloomEnabled = enabled;
  67922. this._buildPipeline();
  67923. },
  67924. enumerable: true,
  67925. configurable: true
  67926. });
  67927. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67928. /**
  67929. * If the depth of field is enabled.
  67930. */
  67931. get: function () {
  67932. return this._depthOfFieldEnabled;
  67933. },
  67934. set: function (enabled) {
  67935. if (this._depthOfFieldEnabled === enabled) {
  67936. return;
  67937. }
  67938. this._depthOfFieldEnabled = enabled;
  67939. this._buildPipeline();
  67940. },
  67941. enumerable: true,
  67942. configurable: true
  67943. });
  67944. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67945. /**
  67946. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67947. */
  67948. get: function () {
  67949. return this._depthOfFieldBlurLevel;
  67950. },
  67951. set: function (value) {
  67952. if (this._depthOfFieldBlurLevel === value) {
  67953. return;
  67954. }
  67955. this._depthOfFieldBlurLevel = value;
  67956. this._buildPipeline();
  67957. },
  67958. enumerable: true,
  67959. configurable: true
  67960. });
  67961. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67962. get: function () {
  67963. return this._fxaaEnabled;
  67964. },
  67965. /**
  67966. * If the anti aliasing is enabled.
  67967. */
  67968. set: function (enabled) {
  67969. if (this._fxaaEnabled === enabled) {
  67970. return;
  67971. }
  67972. this._fxaaEnabled = enabled;
  67973. this._buildPipeline();
  67974. },
  67975. enumerable: true,
  67976. configurable: true
  67977. });
  67978. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  67979. get: function () {
  67980. return this._msaaEnabled;
  67981. },
  67982. /**
  67983. * If the multisample anti-aliasing is enabled.
  67984. */
  67985. set: function (enabled) {
  67986. if (this._msaaEnabled === enabled) {
  67987. return;
  67988. }
  67989. this._msaaEnabled = enabled;
  67990. this._buildPipeline();
  67991. },
  67992. enumerable: true,
  67993. configurable: true
  67994. });
  67995. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67996. get: function () {
  67997. return this._imageProcessingEnabled;
  67998. },
  67999. /**
  68000. * If image processing is enabled.
  68001. */
  68002. set: function (enabled) {
  68003. if (this._imageProcessingEnabled === enabled) {
  68004. return;
  68005. }
  68006. this._imageProcessingEnabled = enabled;
  68007. this._buildPipeline();
  68008. },
  68009. enumerable: true,
  68010. configurable: true
  68011. });
  68012. /**
  68013. * Force the compilation of the entire pipeline.
  68014. */
  68015. DefaultRenderingPipeline.prototype.prepare = function () {
  68016. var previousState = this._buildAllowed;
  68017. this._buildAllowed = true;
  68018. this._buildPipeline();
  68019. this._buildAllowed = previousState;
  68020. };
  68021. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68022. var _this = this;
  68023. if (!this._buildAllowed) {
  68024. return;
  68025. }
  68026. var engine = this._scene.getEngine();
  68027. this._disposePostProcesses();
  68028. this._reset();
  68029. if (this.sharpenEnabled) {
  68030. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68031. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  68032. }
  68033. if (this.depthOfFieldEnabled) {
  68034. // Enable and get current depth map
  68035. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68036. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68037. this.addEffect(this.depthOfField);
  68038. }
  68039. if (this.bloomEnabled) {
  68040. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68041. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68042. if (!this._hdr) {
  68043. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68044. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68045. this.highlights.autoClear = false;
  68046. this.highlights.alwaysForcePOT = true;
  68047. }
  68048. 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);
  68049. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68050. this.blurX.alwaysForcePOT = true;
  68051. this.blurX.autoClear = false;
  68052. this.blurX.onActivateObservable.add(function () {
  68053. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68054. _this.blurX.kernel = _this.bloomKernel * dw;
  68055. });
  68056. 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);
  68057. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68058. this.blurY.alwaysForcePOT = true;
  68059. this.blurY.autoClear = false;
  68060. this.blurY.onActivateObservable.add(function () {
  68061. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68062. _this.blurY.kernel = _this.bloomKernel * dh;
  68063. });
  68064. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68065. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68066. this.copyBack.alwaysForcePOT = true;
  68067. if (this._hdr) {
  68068. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68069. var w = this.bloomWeight;
  68070. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68071. }
  68072. else {
  68073. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68074. }
  68075. this.copyBack.autoClear = false;
  68076. }
  68077. if (this._imageProcessingEnabled) {
  68078. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68079. if (this._hdr) {
  68080. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68081. }
  68082. else {
  68083. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68084. }
  68085. }
  68086. if (this.fxaaEnabled) {
  68087. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68088. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68089. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68090. }
  68091. else if (this._hdr && this.imageProcessing) {
  68092. this.finalMerge = this.imageProcessing;
  68093. }
  68094. else {
  68095. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68096. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68097. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68098. }
  68099. if (this.bloomEnabled) {
  68100. if (this._hdr) {
  68101. this.copyBack.shareOutputWith(this.blurX);
  68102. if (this.imageProcessing) {
  68103. this.imageProcessing.shareOutputWith(this.pass);
  68104. this.imageProcessing.autoClear = false;
  68105. }
  68106. else if (this.fxaa) {
  68107. this.fxaa.shareOutputWith(this.pass);
  68108. }
  68109. else {
  68110. this.finalMerge.shareOutputWith(this.pass);
  68111. }
  68112. }
  68113. else {
  68114. if (this.fxaa) {
  68115. this.fxaa.shareOutputWith(this.pass);
  68116. }
  68117. else {
  68118. this.finalMerge.shareOutputWith(this.pass);
  68119. }
  68120. }
  68121. }
  68122. if (this._cameras !== null) {
  68123. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68124. }
  68125. if (this.msaaEnabled) {
  68126. if (!this._enableMSAAOnFirstPostProcess()) {
  68127. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68128. }
  68129. }
  68130. };
  68131. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68132. for (var i = 0; i < this._cameras.length; i++) {
  68133. var camera = this._cameras[i];
  68134. if (this.sharpen) {
  68135. this.sharpen.dispose(camera);
  68136. }
  68137. if (this.pass) {
  68138. this.pass.dispose(camera);
  68139. }
  68140. if (this.highlights) {
  68141. this.highlights.dispose(camera);
  68142. }
  68143. if (this.blurX) {
  68144. this.blurX.dispose(camera);
  68145. }
  68146. if (this.blurY) {
  68147. this.blurY.dispose(camera);
  68148. }
  68149. if (this.copyBack) {
  68150. this.copyBack.dispose(camera);
  68151. }
  68152. if (this.imageProcessing) {
  68153. this.imageProcessing.dispose(camera);
  68154. }
  68155. if (this.fxaa) {
  68156. this.fxaa.dispose(camera);
  68157. }
  68158. if (this.finalMerge) {
  68159. this.finalMerge.dispose(camera);
  68160. }
  68161. if (this.depthOfField) {
  68162. this.depthOfField.disposeEffects(camera);
  68163. }
  68164. }
  68165. this.sharpen = null;
  68166. this.pass = null;
  68167. this.highlights = null;
  68168. this.blurX = null;
  68169. this.blurY = null;
  68170. this.copyBack = null;
  68171. this.imageProcessing = null;
  68172. this.fxaa = null;
  68173. this.finalMerge = null;
  68174. this.depthOfField = null;
  68175. };
  68176. /**
  68177. * Dispose of the pipeline and stop all post processes
  68178. */
  68179. DefaultRenderingPipeline.prototype.dispose = function () {
  68180. this._disposePostProcesses();
  68181. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68182. _super.prototype.dispose.call(this);
  68183. };
  68184. /**
  68185. * Serialize the rendering pipeline (Used when exporting)
  68186. * @returns the serialized object
  68187. */
  68188. DefaultRenderingPipeline.prototype.serialize = function () {
  68189. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68190. serializationObject.customType = "DefaultRenderingPipeline";
  68191. return serializationObject;
  68192. };
  68193. /**
  68194. * Parse the serialized pipeline
  68195. * @param source Source pipeline.
  68196. * @param scene The scene to load the pipeline to.
  68197. * @param rootUrl The URL of the serialized pipeline.
  68198. * @returns An instantiated pipeline from the serialized object.
  68199. */
  68200. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68201. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68202. };
  68203. __decorate([
  68204. BABYLON.serialize()
  68205. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68206. __decorate([
  68207. BABYLON.serialize()
  68208. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68209. __decorate([
  68210. BABYLON.serialize()
  68211. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68212. __decorate([
  68213. BABYLON.serialize()
  68214. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68215. __decorate([
  68216. BABYLON.serialize()
  68217. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68218. __decorate([
  68219. BABYLON.serialize()
  68220. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68221. __decorate([
  68222. BABYLON.serialize()
  68223. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68224. __decorate([
  68225. BABYLON.serialize()
  68226. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68227. __decorate([
  68228. BABYLON.serialize()
  68229. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68230. __decorate([
  68231. BABYLON.serialize()
  68232. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68233. __decorate([
  68234. BABYLON.serialize()
  68235. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68236. __decorate([
  68237. BABYLON.serialize()
  68238. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68239. return DefaultRenderingPipeline;
  68240. }(BABYLON.PostProcessRenderPipeline));
  68241. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68242. })(BABYLON || (BABYLON = {}));
  68243. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68244. var BABYLON;
  68245. (function (BABYLON) {
  68246. /**
  68247. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68248. */
  68249. var GeometryBufferRenderer = /** @class */ (function () {
  68250. /**
  68251. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68252. * @param scene The scene the buffer belongs to
  68253. * @param ratio How big is the buffer related to the main canvas.
  68254. */
  68255. function GeometryBufferRenderer(scene, ratio) {
  68256. if (ratio === void 0) { ratio = 1; }
  68257. this._enablePosition = false;
  68258. this._scene = scene;
  68259. this._ratio = ratio;
  68260. // Render target
  68261. this._createRenderTargets();
  68262. }
  68263. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68264. /**
  68265. * Set the render list (meshes to be rendered) used in the G buffer.
  68266. */
  68267. set: function (meshes) {
  68268. this._multiRenderTarget.renderList = meshes;
  68269. },
  68270. enumerable: true,
  68271. configurable: true
  68272. });
  68273. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68274. /**
  68275. * Gets wether or not G buffer are supported by the running hardware.
  68276. * This requires draw buffer supports
  68277. */
  68278. get: function () {
  68279. return this._multiRenderTarget.isSupported;
  68280. },
  68281. enumerable: true,
  68282. configurable: true
  68283. });
  68284. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68285. /**
  68286. * Gets wether or not position are enabled for the G buffer.
  68287. */
  68288. get: function () {
  68289. return this._enablePosition;
  68290. },
  68291. /**
  68292. * Sets wether or not position are enabled for the G buffer.
  68293. */
  68294. set: function (enable) {
  68295. this._enablePosition = enable;
  68296. this.dispose();
  68297. this._createRenderTargets();
  68298. },
  68299. enumerable: true,
  68300. configurable: true
  68301. });
  68302. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68303. /**
  68304. * Gets the scene associated with the buffer.
  68305. */
  68306. get: function () {
  68307. return this._scene;
  68308. },
  68309. enumerable: true,
  68310. configurable: true
  68311. });
  68312. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68313. /**
  68314. * Gets the ratio used by the buffer during its creation.
  68315. * How big is the buffer related to the main canvas.
  68316. */
  68317. get: function () {
  68318. return this._ratio;
  68319. },
  68320. enumerable: true,
  68321. configurable: true
  68322. });
  68323. /**
  68324. * Checks wether everything is ready to render a submesh to the G buffer.
  68325. * @param subMesh the submesh to check readiness for
  68326. * @param useInstances is the mesh drawn using instance or not
  68327. * @returns true if ready otherwise false
  68328. */
  68329. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68330. var material = subMesh.getMaterial();
  68331. if (material && material.disableDepthWrite) {
  68332. return false;
  68333. }
  68334. var defines = [];
  68335. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68336. var mesh = subMesh.getMesh();
  68337. // Alpha test
  68338. if (material && material.needAlphaTesting()) {
  68339. defines.push("#define ALPHATEST");
  68340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68341. attribs.push(BABYLON.VertexBuffer.UVKind);
  68342. defines.push("#define UV1");
  68343. }
  68344. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68345. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68346. defines.push("#define UV2");
  68347. }
  68348. }
  68349. // Buffers
  68350. if (this._enablePosition) {
  68351. defines.push("#define POSITION");
  68352. }
  68353. // Bones
  68354. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68355. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68356. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68357. if (mesh.numBoneInfluencers > 4) {
  68358. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68359. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68360. }
  68361. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68362. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68363. }
  68364. else {
  68365. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68366. }
  68367. // Instances
  68368. if (useInstances) {
  68369. defines.push("#define INSTANCES");
  68370. attribs.push("world0");
  68371. attribs.push("world1");
  68372. attribs.push("world2");
  68373. attribs.push("world3");
  68374. }
  68375. // Get correct effect
  68376. var join = defines.join("\n");
  68377. if (this._cachedDefines !== join) {
  68378. this._cachedDefines = join;
  68379. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68380. }
  68381. return this._effect.isReady();
  68382. };
  68383. /**
  68384. * Gets the current underlying G Buffer.
  68385. * @returns the buffer
  68386. */
  68387. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68388. return this._multiRenderTarget;
  68389. };
  68390. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68391. /**
  68392. * Gets the number of samples used to render the buffer (anti aliasing).
  68393. */
  68394. get: function () {
  68395. return this._multiRenderTarget.samples;
  68396. },
  68397. /**
  68398. * Sets the number of samples used to render the buffer (anti aliasing).
  68399. */
  68400. set: function (value) {
  68401. this._multiRenderTarget.samples = value;
  68402. },
  68403. enumerable: true,
  68404. configurable: true
  68405. });
  68406. /**
  68407. * Disposes the renderer and frees up associated resources.
  68408. */
  68409. GeometryBufferRenderer.prototype.dispose = function () {
  68410. this.getGBuffer().dispose();
  68411. };
  68412. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68413. var _this = this;
  68414. var engine = this._scene.getEngine();
  68415. var count = this._enablePosition ? 3 : 2;
  68416. 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 });
  68417. if (!this.isSupported) {
  68418. return;
  68419. }
  68420. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68421. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68422. this._multiRenderTarget.refreshRate = 1;
  68423. this._multiRenderTarget.renderParticles = false;
  68424. this._multiRenderTarget.renderList = null;
  68425. // set default depth value to 1.0 (far away)
  68426. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68427. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68428. });
  68429. // Custom render function
  68430. var renderSubMesh = function (subMesh) {
  68431. var mesh = subMesh.getRenderingMesh();
  68432. var scene = _this._scene;
  68433. var engine = scene.getEngine();
  68434. var material = subMesh.getMaterial();
  68435. if (!material) {
  68436. return;
  68437. }
  68438. // Culling
  68439. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68440. // Managing instances
  68441. var batch = mesh._getInstancesRenderList(subMesh._id);
  68442. if (batch.mustReturn) {
  68443. return;
  68444. }
  68445. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68446. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68447. engine.enableEffect(_this._effect);
  68448. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68449. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68450. _this._effect.setMatrix("view", scene.getViewMatrix());
  68451. // Alpha test
  68452. if (material && material.needAlphaTesting()) {
  68453. var alphaTexture = material.getAlphaTestTexture();
  68454. if (alphaTexture) {
  68455. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68456. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68457. }
  68458. }
  68459. // Bones
  68460. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68461. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68462. }
  68463. // Draw
  68464. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68465. }
  68466. };
  68467. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68468. var index;
  68469. if (depthOnlySubMeshes.length) {
  68470. engine.setColorWrite(false);
  68471. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68472. renderSubMesh(depthOnlySubMeshes.data[index]);
  68473. }
  68474. engine.setColorWrite(true);
  68475. }
  68476. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68477. renderSubMesh(opaqueSubMeshes.data[index]);
  68478. }
  68479. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68480. renderSubMesh(alphaTestSubMeshes.data[index]);
  68481. }
  68482. };
  68483. };
  68484. return GeometryBufferRenderer;
  68485. }());
  68486. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68487. })(BABYLON || (BABYLON = {}));
  68488. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68489. var BABYLON;
  68490. (function (BABYLON) {
  68491. var RefractionPostProcess = /** @class */ (function (_super) {
  68492. __extends(RefractionPostProcess, _super);
  68493. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68494. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68495. _this.color = color;
  68496. _this.depth = depth;
  68497. _this.colorLevel = colorLevel;
  68498. _this._ownRefractionTexture = true;
  68499. _this.onActivateObservable.add(function (cam) {
  68500. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68501. });
  68502. _this.onApplyObservable.add(function (effect) {
  68503. effect.setColor3("baseColor", _this.color);
  68504. effect.setFloat("depth", _this.depth);
  68505. effect.setFloat("colorLevel", _this.colorLevel);
  68506. effect.setTexture("refractionSampler", _this._refTexture);
  68507. });
  68508. return _this;
  68509. }
  68510. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68511. /**
  68512. * Gets or sets the refraction texture
  68513. * Please note that you are responsible for disposing the texture if you set it manually
  68514. */
  68515. get: function () {
  68516. return this._refTexture;
  68517. },
  68518. set: function (value) {
  68519. if (this._refTexture && this._ownRefractionTexture) {
  68520. this._refTexture.dispose();
  68521. }
  68522. this._refTexture = value;
  68523. this._ownRefractionTexture = false;
  68524. },
  68525. enumerable: true,
  68526. configurable: true
  68527. });
  68528. // Methods
  68529. RefractionPostProcess.prototype.dispose = function (camera) {
  68530. if (this._refTexture && this._ownRefractionTexture) {
  68531. this._refTexture.dispose();
  68532. this._refTexture = null;
  68533. }
  68534. _super.prototype.dispose.call(this, camera);
  68535. };
  68536. return RefractionPostProcess;
  68537. }(BABYLON.PostProcess));
  68538. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68539. })(BABYLON || (BABYLON = {}));
  68540. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68541. var BABYLON;
  68542. (function (BABYLON) {
  68543. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68544. __extends(BlackAndWhitePostProcess, _super);
  68545. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68546. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68547. _this.degree = 1;
  68548. _this.onApplyObservable.add(function (effect) {
  68549. effect.setFloat("degree", _this.degree);
  68550. });
  68551. return _this;
  68552. }
  68553. return BlackAndWhitePostProcess;
  68554. }(BABYLON.PostProcess));
  68555. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68556. })(BABYLON || (BABYLON = {}));
  68557. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68558. var BABYLON;
  68559. (function (BABYLON) {
  68560. /**
  68561. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68562. * input texture to perform effects such as edge detection or sharpening
  68563. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68564. */
  68565. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68566. __extends(ConvolutionPostProcess, _super);
  68567. /**
  68568. * Creates a new instance of @see ConvolutionPostProcess
  68569. * @param name The name of the effect.
  68570. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68571. * @param options The required width/height ratio to downsize to before computing the render pass.
  68572. * @param camera The camera to apply the render pass to.
  68573. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68574. * @param engine The engine which the post process will be applied. (default: current engine)
  68575. * @param reusable If the post process can be reused on the same frame. (default: false)
  68576. * @param textureType Type of textures used when performing the post process. (default: 0)
  68577. */
  68578. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68580. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68581. _this.kernel = kernel;
  68582. _this.onApply = function (effect) {
  68583. effect.setFloat2("screenSize", _this.width, _this.height);
  68584. effect.setArray("kernel", _this.kernel);
  68585. };
  68586. return _this;
  68587. }
  68588. // Statics
  68589. /**
  68590. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68591. */
  68592. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68593. /**
  68594. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68595. */
  68596. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68597. /**
  68598. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68599. */
  68600. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68601. /**
  68602. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68603. */
  68604. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68605. /**
  68606. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68607. */
  68608. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68609. /**
  68610. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68611. */
  68612. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68613. return ConvolutionPostProcess;
  68614. }(BABYLON.PostProcess));
  68615. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68616. })(BABYLON || (BABYLON = {}));
  68617. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68618. var BABYLON;
  68619. (function (BABYLON) {
  68620. /**
  68621. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68622. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68623. */
  68624. var SharpenPostProcess = /** @class */ (function (_super) {
  68625. __extends(SharpenPostProcess, _super);
  68626. /**
  68627. * Creates a new instance of @see ConvolutionPostProcess
  68628. * @param name The name of the effect.
  68629. * @param options The required width/height ratio to downsize to before computing the render pass.
  68630. * @param camera The camera to apply the render pass to.
  68631. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68632. * @param engine The engine which the post process will be applied. (default: current engine)
  68633. * @param reusable If the post process can be reused on the same frame. (default: false)
  68634. * @param textureType Type of textures used when performing the post process. (default: 0)
  68635. */
  68636. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68637. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68638. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68639. /**
  68640. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68641. */
  68642. _this.colorAmount = 1.0;
  68643. /**
  68644. * How much sharpness should be applied (default: 0.3)
  68645. */
  68646. _this.edgeAmount = 0.3;
  68647. _this.onApply = function (effect) {
  68648. effect.setFloat2("screenSize", _this.width, _this.height);
  68649. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68650. };
  68651. return _this;
  68652. }
  68653. return SharpenPostProcess;
  68654. }(BABYLON.PostProcess));
  68655. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68656. })(BABYLON || (BABYLON = {}));
  68657. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68658. var BABYLON;
  68659. (function (BABYLON) {
  68660. var FilterPostProcess = /** @class */ (function (_super) {
  68661. __extends(FilterPostProcess, _super);
  68662. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68663. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68664. _this.kernelMatrix = kernelMatrix;
  68665. _this.onApply = function (effect) {
  68666. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68667. };
  68668. return _this;
  68669. }
  68670. return FilterPostProcess;
  68671. }(BABYLON.PostProcess));
  68672. BABYLON.FilterPostProcess = FilterPostProcess;
  68673. })(BABYLON || (BABYLON = {}));
  68674. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68675. var BABYLON;
  68676. (function (BABYLON) {
  68677. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68678. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68679. __extends(VolumetricLightScatteringPostProcess, _super);
  68680. /**
  68681. * @constructor
  68682. * @param {string} name - The post-process name
  68683. * @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)
  68684. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68685. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68686. * @param {number} samples - The post-process quality, default 100
  68687. * @param {number} samplingMode - The post-process filtering mode
  68688. * @param {BABYLON.Engine} engine - The babylon engine
  68689. * @param {boolean} reusable - If the post-process is reusable
  68690. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68691. */
  68692. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68693. if (samples === void 0) { samples = 100; }
  68694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68695. 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;
  68696. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68697. /**
  68698. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68699. * @type {Vector3}
  68700. */
  68701. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68702. /**
  68703. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68704. * @type {boolean}
  68705. */
  68706. _this.useCustomMeshPosition = false;
  68707. /**
  68708. * If the post-process should inverse the light scattering direction
  68709. * @type {boolean}
  68710. */
  68711. _this.invert = true;
  68712. /**
  68713. * Array containing the excluded meshes not rendered in the internal pass
  68714. */
  68715. _this.excludedMeshes = new Array();
  68716. /**
  68717. * Controls the overall intensity of the post-process
  68718. * @type {number}
  68719. */
  68720. _this.exposure = 0.3;
  68721. /**
  68722. * Dissipates each sample's contribution in range [0, 1]
  68723. * @type {number}
  68724. */
  68725. _this.decay = 0.96815;
  68726. /**
  68727. * Controls the overall intensity of each sample
  68728. * @type {number}
  68729. */
  68730. _this.weight = 0.58767;
  68731. /**
  68732. * Controls the density of each sample
  68733. * @type {number}
  68734. */
  68735. _this.density = 0.926;
  68736. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68737. engine = scene.getEngine();
  68738. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68739. // Configure mesh
  68740. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68741. // Configure
  68742. _this._createPass(scene, ratio.passRatio || ratio);
  68743. _this.onActivate = function (camera) {
  68744. if (!_this.isSupported) {
  68745. _this.dispose(camera);
  68746. }
  68747. _this.onActivate = null;
  68748. };
  68749. _this.onApplyObservable.add(function (effect) {
  68750. _this._updateMeshScreenCoordinates(scene);
  68751. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68752. effect.setFloat("exposure", _this.exposure);
  68753. effect.setFloat("decay", _this.decay);
  68754. effect.setFloat("weight", _this.weight);
  68755. effect.setFloat("density", _this.density);
  68756. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68757. });
  68758. return _this;
  68759. }
  68760. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68761. get: function () {
  68762. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68763. return false;
  68764. },
  68765. set: function (useDiffuseColor) {
  68766. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68767. },
  68768. enumerable: true,
  68769. configurable: true
  68770. });
  68771. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68772. return "VolumetricLightScatteringPostProcess";
  68773. };
  68774. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68775. var mesh = subMesh.getMesh();
  68776. // Render this.mesh as default
  68777. if (mesh === this.mesh && mesh.material) {
  68778. return mesh.material.isReady(mesh);
  68779. }
  68780. var defines = [];
  68781. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68782. var material = subMesh.getMaterial();
  68783. // Alpha test
  68784. if (material) {
  68785. if (material.needAlphaTesting()) {
  68786. defines.push("#define ALPHATEST");
  68787. }
  68788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68789. attribs.push(BABYLON.VertexBuffer.UVKind);
  68790. defines.push("#define UV1");
  68791. }
  68792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68793. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68794. defines.push("#define UV2");
  68795. }
  68796. }
  68797. // Bones
  68798. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68801. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68802. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68803. }
  68804. else {
  68805. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68806. }
  68807. // Instances
  68808. if (useInstances) {
  68809. defines.push("#define INSTANCES");
  68810. attribs.push("world0");
  68811. attribs.push("world1");
  68812. attribs.push("world2");
  68813. attribs.push("world3");
  68814. }
  68815. // Get correct effect
  68816. var join = defines.join("\n");
  68817. if (this._cachedDefines !== join) {
  68818. this._cachedDefines = join;
  68819. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68820. }
  68821. return this._volumetricLightScatteringPass.isReady();
  68822. };
  68823. /**
  68824. * Sets the new light position for light scattering effect
  68825. * @param {BABYLON.Vector3} The new custom light position
  68826. */
  68827. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68828. this.customMeshPosition = position;
  68829. };
  68830. /**
  68831. * Returns the light position for light scattering effect
  68832. * @return {BABYLON.Vector3} The custom light position
  68833. */
  68834. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68835. return this.customMeshPosition;
  68836. };
  68837. /**
  68838. * Disposes the internal assets and detaches the post-process from the camera
  68839. */
  68840. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68841. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68842. if (rttIndex !== -1) {
  68843. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68844. }
  68845. this._volumetricLightScatteringRTT.dispose();
  68846. _super.prototype.dispose.call(this, camera);
  68847. };
  68848. /**
  68849. * Returns the render target texture used by the post-process
  68850. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68851. */
  68852. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68853. return this._volumetricLightScatteringRTT;
  68854. };
  68855. // Private methods
  68856. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68857. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68858. return true;
  68859. }
  68860. return false;
  68861. };
  68862. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68863. var _this = this;
  68864. var engine = scene.getEngine();
  68865. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68866. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68867. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68868. this._volumetricLightScatteringRTT.renderList = null;
  68869. this._volumetricLightScatteringRTT.renderParticles = false;
  68870. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68871. var camera = this.getCamera();
  68872. if (camera) {
  68873. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68874. }
  68875. else {
  68876. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68877. }
  68878. // Custom render function for submeshes
  68879. var renderSubMesh = function (subMesh) {
  68880. var mesh = subMesh.getRenderingMesh();
  68881. if (_this._meshExcluded(mesh)) {
  68882. return;
  68883. }
  68884. var material = subMesh.getMaterial();
  68885. if (!material) {
  68886. return;
  68887. }
  68888. var scene = mesh.getScene();
  68889. var engine = scene.getEngine();
  68890. // Culling
  68891. engine.setState(material.backFaceCulling);
  68892. // Managing instances
  68893. var batch = mesh._getInstancesRenderList(subMesh._id);
  68894. if (batch.mustReturn) {
  68895. return;
  68896. }
  68897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68898. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68899. var effect = _this._volumetricLightScatteringPass;
  68900. if (mesh === _this.mesh) {
  68901. if (subMesh.effect) {
  68902. effect = subMesh.effect;
  68903. }
  68904. else {
  68905. effect = material.getEffect();
  68906. }
  68907. }
  68908. engine.enableEffect(effect);
  68909. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68910. if (mesh === _this.mesh) {
  68911. material.bind(mesh.getWorldMatrix(), mesh);
  68912. }
  68913. else {
  68914. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68915. // Alpha test
  68916. if (material && material.needAlphaTesting()) {
  68917. var alphaTexture = material.getAlphaTestTexture();
  68918. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68919. if (alphaTexture) {
  68920. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68921. }
  68922. }
  68923. // Bones
  68924. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68925. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68926. }
  68927. }
  68928. // Draw
  68929. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68930. }
  68931. };
  68932. // Render target texture callbacks
  68933. var savedSceneClearColor;
  68934. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68935. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68936. savedSceneClearColor = scene.clearColor;
  68937. scene.clearColor = sceneClearColor;
  68938. });
  68939. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68940. scene.clearColor = savedSceneClearColor;
  68941. });
  68942. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68943. var engine = scene.getEngine();
  68944. var index;
  68945. if (depthOnlySubMeshes.length) {
  68946. engine.setColorWrite(false);
  68947. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68948. renderSubMesh(depthOnlySubMeshes.data[index]);
  68949. }
  68950. engine.setColorWrite(true);
  68951. }
  68952. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68953. renderSubMesh(opaqueSubMeshes.data[index]);
  68954. }
  68955. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68956. renderSubMesh(alphaTestSubMeshes.data[index]);
  68957. }
  68958. if (transparentSubMeshes.length) {
  68959. // Sort sub meshes
  68960. for (index = 0; index < transparentSubMeshes.length; index++) {
  68961. var submesh = transparentSubMeshes.data[index];
  68962. var boundingInfo = submesh.getBoundingInfo();
  68963. if (boundingInfo && scene.activeCamera) {
  68964. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68965. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68966. }
  68967. }
  68968. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68969. sortedArray.sort(function (a, b) {
  68970. // Alpha index first
  68971. if (a._alphaIndex > b._alphaIndex) {
  68972. return 1;
  68973. }
  68974. if (a._alphaIndex < b._alphaIndex) {
  68975. return -1;
  68976. }
  68977. // Then distance to camera
  68978. if (a._distanceToCamera < b._distanceToCamera) {
  68979. return 1;
  68980. }
  68981. if (a._distanceToCamera > b._distanceToCamera) {
  68982. return -1;
  68983. }
  68984. return 0;
  68985. });
  68986. // Render sub meshes
  68987. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68988. for (index = 0; index < sortedArray.length; index++) {
  68989. renderSubMesh(sortedArray[index]);
  68990. }
  68991. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68992. }
  68993. };
  68994. };
  68995. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68996. var transform = scene.getTransformMatrix();
  68997. var meshPosition;
  68998. if (this.useCustomMeshPosition) {
  68999. meshPosition = this.customMeshPosition;
  69000. }
  69001. else if (this.attachedNode) {
  69002. meshPosition = this.attachedNode.position;
  69003. }
  69004. else {
  69005. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69006. }
  69007. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69008. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69009. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69010. if (this.invert)
  69011. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69012. };
  69013. // Static methods
  69014. /**
  69015. * Creates a default mesh for the Volumeric Light Scattering post-process
  69016. * @param {string} The mesh name
  69017. * @param {BABYLON.Scene} The scene where to create the mesh
  69018. * @return {BABYLON.Mesh} the default mesh
  69019. */
  69020. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69021. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69022. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69023. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69024. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69025. mesh.material = material;
  69026. return mesh;
  69027. };
  69028. __decorate([
  69029. BABYLON.serializeAsVector3()
  69030. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69031. __decorate([
  69032. BABYLON.serialize()
  69033. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69034. __decorate([
  69035. BABYLON.serialize()
  69036. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69037. __decorate([
  69038. BABYLON.serializeAsMeshReference()
  69039. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69040. __decorate([
  69041. BABYLON.serialize()
  69042. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69043. __decorate([
  69044. BABYLON.serialize()
  69045. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69046. __decorate([
  69047. BABYLON.serialize()
  69048. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69049. __decorate([
  69050. BABYLON.serialize()
  69051. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69052. __decorate([
  69053. BABYLON.serialize()
  69054. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69055. return VolumetricLightScatteringPostProcess;
  69056. }(BABYLON.PostProcess));
  69057. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69058. })(BABYLON || (BABYLON = {}));
  69059. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69060. //
  69061. // This post-process allows the modification of rendered colors by using
  69062. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69063. //
  69064. // The object needs to be provided an url to a texture containing the color
  69065. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69066. // Use an image editing software to tweak the LUT to match your needs.
  69067. //
  69068. // For an example of a color LUT, see here:
  69069. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69070. // For explanations on color grading, see here:
  69071. // http://udn.epicgames.com/Three/ColorGrading.html
  69072. //
  69073. var BABYLON;
  69074. (function (BABYLON) {
  69075. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69076. __extends(ColorCorrectionPostProcess, _super);
  69077. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69078. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69079. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69080. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69081. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69082. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69083. _this.onApply = function (effect) {
  69084. effect.setTexture("colorTable", _this._colorTableTexture);
  69085. };
  69086. return _this;
  69087. }
  69088. return ColorCorrectionPostProcess;
  69089. }(BABYLON.PostProcess));
  69090. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69091. })(BABYLON || (BABYLON = {}));
  69092. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69093. var BABYLON;
  69094. (function (BABYLON) {
  69095. var TonemappingOperator;
  69096. (function (TonemappingOperator) {
  69097. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69098. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69099. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69100. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69101. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69102. ;
  69103. var TonemapPostProcess = /** @class */ (function (_super) {
  69104. __extends(TonemapPostProcess, _super);
  69105. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69107. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69108. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69109. _this._operator = _operator;
  69110. _this.exposureAdjustment = exposureAdjustment;
  69111. var defines = "#define ";
  69112. if (_this._operator === TonemappingOperator.Hable)
  69113. defines += "HABLE_TONEMAPPING";
  69114. else if (_this._operator === TonemappingOperator.Reinhard)
  69115. defines += "REINHARD_TONEMAPPING";
  69116. else if (_this._operator === TonemappingOperator.HejiDawson)
  69117. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69118. else if (_this._operator === TonemappingOperator.Photographic)
  69119. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69120. //sadly a second call to create the effect.
  69121. _this.updateEffect(defines);
  69122. _this.onApply = function (effect) {
  69123. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69124. };
  69125. return _this;
  69126. }
  69127. return TonemapPostProcess;
  69128. }(BABYLON.PostProcess));
  69129. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69130. })(BABYLON || (BABYLON = {}));
  69131. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69132. var BABYLON;
  69133. (function (BABYLON) {
  69134. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69135. __extends(DisplayPassPostProcess, _super);
  69136. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69137. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69138. }
  69139. return DisplayPassPostProcess;
  69140. }(BABYLON.PostProcess));
  69141. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69142. })(BABYLON || (BABYLON = {}));
  69143. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69144. var BABYLON;
  69145. (function (BABYLON) {
  69146. var HighlightsPostProcess = /** @class */ (function (_super) {
  69147. __extends(HighlightsPostProcess, _super);
  69148. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69149. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69150. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69151. }
  69152. return HighlightsPostProcess;
  69153. }(BABYLON.PostProcess));
  69154. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69155. })(BABYLON || (BABYLON = {}));
  69156. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69157. var BABYLON;
  69158. (function (BABYLON) {
  69159. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69160. __extends(ImageProcessingPostProcess, _super);
  69161. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69162. if (camera === void 0) { camera = null; }
  69163. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69164. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69165. _this._fromLinearSpace = true;
  69166. /**
  69167. * Defines cache preventing GC.
  69168. */
  69169. _this._defines = {
  69170. IMAGEPROCESSING: false,
  69171. VIGNETTE: false,
  69172. VIGNETTEBLENDMODEMULTIPLY: false,
  69173. VIGNETTEBLENDMODEOPAQUE: false,
  69174. TONEMAPPING: false,
  69175. CONTRAST: false,
  69176. COLORCURVES: false,
  69177. COLORGRADING: false,
  69178. COLORGRADING3D: false,
  69179. FROMLINEARSPACE: false,
  69180. SAMPLER3DGREENDEPTH: false,
  69181. SAMPLER3DBGRMAP: false,
  69182. IMAGEPROCESSINGPOSTPROCESS: false,
  69183. EXPOSURE: false,
  69184. };
  69185. // Setup the configuration as forced by the constructor. This would then not force the
  69186. // scene materials output in linear space and let untouched the default forward pass.
  69187. if (imageProcessingConfiguration) {
  69188. imageProcessingConfiguration.applyByPostProcess = true;
  69189. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69190. // This will cause the shader to be compiled
  69191. _this.fromLinearSpace = false;
  69192. }
  69193. else {
  69194. _this._attachImageProcessingConfiguration(null, true);
  69195. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69196. }
  69197. _this.onApply = function (effect) {
  69198. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69199. };
  69200. return _this;
  69201. }
  69202. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69203. /**
  69204. * Gets the image processing configuration used either in this material.
  69205. */
  69206. get: function () {
  69207. return this._imageProcessingConfiguration;
  69208. },
  69209. /**
  69210. * Sets the Default image processing configuration used either in the this material.
  69211. *
  69212. * If sets to null, the scene one is in use.
  69213. */
  69214. set: function (value) {
  69215. this._attachImageProcessingConfiguration(value);
  69216. },
  69217. enumerable: true,
  69218. configurable: true
  69219. });
  69220. /**
  69221. * Attaches a new image processing configuration to the PBR Material.
  69222. * @param configuration
  69223. */
  69224. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69225. var _this = this;
  69226. if (doNotBuild === void 0) { doNotBuild = false; }
  69227. if (configuration === this._imageProcessingConfiguration) {
  69228. return;
  69229. }
  69230. // Detaches observer.
  69231. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69232. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69233. }
  69234. // Pick the scene configuration if needed.
  69235. if (!configuration) {
  69236. var scene = null;
  69237. var engine = this.getEngine();
  69238. var camera = this.getCamera();
  69239. if (camera) {
  69240. scene = camera.getScene();
  69241. }
  69242. else if (engine && engine.scenes) {
  69243. var scenes = engine.scenes;
  69244. scene = scenes[scenes.length - 1];
  69245. }
  69246. else {
  69247. scene = BABYLON.Engine.LastCreatedScene;
  69248. }
  69249. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69250. }
  69251. else {
  69252. this._imageProcessingConfiguration = configuration;
  69253. }
  69254. // Attaches observer.
  69255. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69256. _this._updateParameters();
  69257. });
  69258. // Ensure the effect will be rebuilt.
  69259. if (!doNotBuild) {
  69260. this._updateParameters();
  69261. }
  69262. };
  69263. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69264. /**
  69265. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69266. */
  69267. get: function () {
  69268. return this.imageProcessingConfiguration.colorCurves;
  69269. },
  69270. /**
  69271. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69272. */
  69273. set: function (value) {
  69274. this.imageProcessingConfiguration.colorCurves = value;
  69275. },
  69276. enumerable: true,
  69277. configurable: true
  69278. });
  69279. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69280. /**
  69281. * Gets wether the color curves effect is enabled.
  69282. */
  69283. get: function () {
  69284. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69285. },
  69286. /**
  69287. * Sets wether the color curves effect is enabled.
  69288. */
  69289. set: function (value) {
  69290. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69291. },
  69292. enumerable: true,
  69293. configurable: true
  69294. });
  69295. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69296. /**
  69297. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69298. */
  69299. get: function () {
  69300. return this.imageProcessingConfiguration.colorGradingTexture;
  69301. },
  69302. /**
  69303. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69304. */
  69305. set: function (value) {
  69306. this.imageProcessingConfiguration.colorGradingTexture = value;
  69307. },
  69308. enumerable: true,
  69309. configurable: true
  69310. });
  69311. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69312. /**
  69313. * Gets wether the color grading effect is enabled.
  69314. */
  69315. get: function () {
  69316. return this.imageProcessingConfiguration.colorGradingEnabled;
  69317. },
  69318. /**
  69319. * Gets wether the color grading effect is enabled.
  69320. */
  69321. set: function (value) {
  69322. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69323. },
  69324. enumerable: true,
  69325. configurable: true
  69326. });
  69327. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69328. /**
  69329. * Gets exposure used in the effect.
  69330. */
  69331. get: function () {
  69332. return this.imageProcessingConfiguration.exposure;
  69333. },
  69334. /**
  69335. * Sets exposure used in the effect.
  69336. */
  69337. set: function (value) {
  69338. this.imageProcessingConfiguration.exposure = value;
  69339. },
  69340. enumerable: true,
  69341. configurable: true
  69342. });
  69343. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69344. /**
  69345. * Gets wether tonemapping is enabled or not.
  69346. */
  69347. get: function () {
  69348. return this._imageProcessingConfiguration.toneMappingEnabled;
  69349. },
  69350. /**
  69351. * Sets wether tonemapping is enabled or not
  69352. */
  69353. set: function (value) {
  69354. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69355. },
  69356. enumerable: true,
  69357. configurable: true
  69358. });
  69359. ;
  69360. ;
  69361. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69362. /**
  69363. * Gets contrast used in the effect.
  69364. */
  69365. get: function () {
  69366. return this.imageProcessingConfiguration.contrast;
  69367. },
  69368. /**
  69369. * Sets contrast used in the effect.
  69370. */
  69371. set: function (value) {
  69372. this.imageProcessingConfiguration.contrast = value;
  69373. },
  69374. enumerable: true,
  69375. configurable: true
  69376. });
  69377. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69378. /**
  69379. * Gets Vignette stretch size.
  69380. */
  69381. get: function () {
  69382. return this.imageProcessingConfiguration.vignetteStretch;
  69383. },
  69384. /**
  69385. * Sets Vignette stretch size.
  69386. */
  69387. set: function (value) {
  69388. this.imageProcessingConfiguration.vignetteStretch = value;
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69394. /**
  69395. * Gets Vignette centre X Offset.
  69396. */
  69397. get: function () {
  69398. return this.imageProcessingConfiguration.vignetteCentreX;
  69399. },
  69400. /**
  69401. * Sets Vignette centre X Offset.
  69402. */
  69403. set: function (value) {
  69404. this.imageProcessingConfiguration.vignetteCentreX = value;
  69405. },
  69406. enumerable: true,
  69407. configurable: true
  69408. });
  69409. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69410. /**
  69411. * Gets Vignette centre Y Offset.
  69412. */
  69413. get: function () {
  69414. return this.imageProcessingConfiguration.vignetteCentreY;
  69415. },
  69416. /**
  69417. * Sets Vignette centre Y Offset.
  69418. */
  69419. set: function (value) {
  69420. this.imageProcessingConfiguration.vignetteCentreY = value;
  69421. },
  69422. enumerable: true,
  69423. configurable: true
  69424. });
  69425. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69426. /**
  69427. * Gets Vignette weight or intensity of the vignette effect.
  69428. */
  69429. get: function () {
  69430. return this.imageProcessingConfiguration.vignetteWeight;
  69431. },
  69432. /**
  69433. * Sets Vignette weight or intensity of the vignette effect.
  69434. */
  69435. set: function (value) {
  69436. this.imageProcessingConfiguration.vignetteWeight = value;
  69437. },
  69438. enumerable: true,
  69439. configurable: true
  69440. });
  69441. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69442. /**
  69443. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69444. * if vignetteEnabled is set to true.
  69445. */
  69446. get: function () {
  69447. return this.imageProcessingConfiguration.vignetteColor;
  69448. },
  69449. /**
  69450. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69451. * if vignetteEnabled is set to true.
  69452. */
  69453. set: function (value) {
  69454. this.imageProcessingConfiguration.vignetteColor = value;
  69455. },
  69456. enumerable: true,
  69457. configurable: true
  69458. });
  69459. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69460. /**
  69461. * Gets Camera field of view used by the Vignette effect.
  69462. */
  69463. get: function () {
  69464. return this.imageProcessingConfiguration.vignetteCameraFov;
  69465. },
  69466. /**
  69467. * Sets Camera field of view used by the Vignette effect.
  69468. */
  69469. set: function (value) {
  69470. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69471. },
  69472. enumerable: true,
  69473. configurable: true
  69474. });
  69475. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69476. /**
  69477. * Gets the vignette blend mode allowing different kind of effect.
  69478. */
  69479. get: function () {
  69480. return this.imageProcessingConfiguration.vignetteBlendMode;
  69481. },
  69482. /**
  69483. * Sets the vignette blend mode allowing different kind of effect.
  69484. */
  69485. set: function (value) {
  69486. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69487. },
  69488. enumerable: true,
  69489. configurable: true
  69490. });
  69491. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69492. /**
  69493. * Gets wether the vignette effect is enabled.
  69494. */
  69495. get: function () {
  69496. return this.imageProcessingConfiguration.vignetteEnabled;
  69497. },
  69498. /**
  69499. * Sets wether the vignette effect is enabled.
  69500. */
  69501. set: function (value) {
  69502. this.imageProcessingConfiguration.vignetteEnabled = value;
  69503. },
  69504. enumerable: true,
  69505. configurable: true
  69506. });
  69507. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69508. /**
  69509. * Gets wether the input of the processing is in Gamma or Linear Space.
  69510. */
  69511. get: function () {
  69512. return this._fromLinearSpace;
  69513. },
  69514. /**
  69515. * Sets wether the input of the processing is in Gamma or Linear Space.
  69516. */
  69517. set: function (value) {
  69518. if (this._fromLinearSpace === value) {
  69519. return;
  69520. }
  69521. this._fromLinearSpace = value;
  69522. this._updateParameters();
  69523. },
  69524. enumerable: true,
  69525. configurable: true
  69526. });
  69527. ImageProcessingPostProcess.prototype.getClassName = function () {
  69528. return "ImageProcessingPostProcess";
  69529. };
  69530. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69531. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69532. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69533. var defines = "";
  69534. for (var define in this._defines) {
  69535. if (this._defines[define]) {
  69536. defines += "#define " + define + ";\r\n";
  69537. }
  69538. }
  69539. var samplers = ["textureSampler"];
  69540. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69541. var uniforms = ["scale"];
  69542. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69543. this.updateEffect(defines, uniforms, samplers);
  69544. };
  69545. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69546. _super.prototype.dispose.call(this, camera);
  69547. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69548. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69549. }
  69550. this.imageProcessingConfiguration.applyByPostProcess = false;
  69551. };
  69552. __decorate([
  69553. BABYLON.serialize()
  69554. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69555. return ImageProcessingPostProcess;
  69556. }(BABYLON.PostProcess));
  69557. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69558. })(BABYLON || (BABYLON = {}));
  69559. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69560. var BABYLON;
  69561. (function (BABYLON) {
  69562. /**
  69563. * The Blur Post Process which blurs an image based on a kernel and direction.
  69564. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69565. */
  69566. var BlurPostProcess = /** @class */ (function (_super) {
  69567. __extends(BlurPostProcess, _super);
  69568. /**
  69569. * Creates a new instance of @see BlurPostProcess
  69570. * @param name The name of the effect.
  69571. * @param direction The direction in which to blur the image.
  69572. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  69573. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69574. * @param camera The camera to apply the render pass to.
  69575. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69576. * @param engine The engine which the post process will be applied. (default: current engine)
  69577. * @param reusable If the post process can be reused on the same frame. (default: false)
  69578. * @param textureType Type of textures used when performing the post process. (default: 0)
  69579. */
  69580. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69582. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69583. if (defines === void 0) { defines = ""; }
  69584. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  69585. _this.direction = direction;
  69586. _this._packedFloat = false;
  69587. _this._staticDefines = "";
  69588. _this._staticDefines = defines;
  69589. _this.onApplyObservable.add(function (effect) {
  69590. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69591. });
  69592. _this.kernel = kernel;
  69593. return _this;
  69594. }
  69595. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69596. /**
  69597. * Gets the length in pixels of the blur sample region
  69598. */
  69599. get: function () {
  69600. return this._idealKernel;
  69601. },
  69602. /**
  69603. * Sets the length in pixels of the blur sample region
  69604. */
  69605. set: function (v) {
  69606. if (this._idealKernel === v) {
  69607. return;
  69608. }
  69609. v = Math.max(v, 1);
  69610. this._idealKernel = v;
  69611. this._kernel = this._nearestBestKernel(v);
  69612. this._updateParameters();
  69613. },
  69614. enumerable: true,
  69615. configurable: true
  69616. });
  69617. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69618. /**
  69619. * Gets wether or not the blur is unpacking/repacking floats
  69620. */
  69621. get: function () {
  69622. return this._packedFloat;
  69623. },
  69624. /**
  69625. * Sets wether or not the blur needs to unpack/repack floats
  69626. */
  69627. set: function (v) {
  69628. if (this._packedFloat === v) {
  69629. return;
  69630. }
  69631. this._packedFloat = v;
  69632. this._updateParameters();
  69633. },
  69634. enumerable: true,
  69635. configurable: true
  69636. });
  69637. BlurPostProcess.prototype._updateParameters = function () {
  69638. // Generate sampling offsets and weights
  69639. var N = this._kernel;
  69640. var centerIndex = (N - 1) / 2;
  69641. // Generate Gaussian sampling weights over kernel
  69642. var offsets = [];
  69643. var weights = [];
  69644. var totalWeight = 0;
  69645. for (var i = 0; i < N; i++) {
  69646. var u = i / (N - 1);
  69647. var w = this._gaussianWeight(u * 2.0 - 1);
  69648. offsets[i] = (i - centerIndex);
  69649. weights[i] = w;
  69650. totalWeight += w;
  69651. }
  69652. // Normalize weights
  69653. for (var i = 0; i < weights.length; i++) {
  69654. weights[i] /= totalWeight;
  69655. }
  69656. // Optimize: combine samples to take advantage of hardware linear sampling
  69657. // Walk from left to center, combining pairs (symmetrically)
  69658. var linearSamplingWeights = [];
  69659. var linearSamplingOffsets = [];
  69660. var linearSamplingMap = [];
  69661. for (var i = 0; i <= centerIndex; i += 2) {
  69662. var j = Math.min(i + 1, Math.floor(centerIndex));
  69663. var singleCenterSample = i === j;
  69664. if (singleCenterSample) {
  69665. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69666. }
  69667. else {
  69668. var sharedCell = j === centerIndex;
  69669. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69670. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69671. if (offsetLinear === 0) {
  69672. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69673. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69674. }
  69675. else {
  69676. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69677. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69678. }
  69679. }
  69680. }
  69681. for (var i = 0; i < linearSamplingMap.length; i++) {
  69682. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69683. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69684. }
  69685. // Replace with optimized
  69686. offsets = linearSamplingOffsets;
  69687. weights = linearSamplingWeights;
  69688. // Generate shaders
  69689. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69690. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69691. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69692. var defines = "";
  69693. defines += this._staticDefines;
  69694. for (var i = 0; i < varyingCount; i++) {
  69695. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69696. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69697. }
  69698. var depCount = 0;
  69699. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69700. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69701. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69702. depCount++;
  69703. }
  69704. if (this.packedFloat) {
  69705. defines += "#define PACKEDFLOAT 1";
  69706. }
  69707. this.updateEffect(defines, null, null, {
  69708. varyingCount: varyingCount,
  69709. depCount: depCount
  69710. });
  69711. };
  69712. /**
  69713. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69714. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69715. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69716. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69717. * The gaps between physical kernels are compensated for in the weighting of the samples
  69718. * @param idealKernel Ideal blur kernel.
  69719. * @return Nearest best kernel.
  69720. */
  69721. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69722. var v = Math.round(idealKernel);
  69723. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69724. var k = _a[_i];
  69725. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69726. return Math.max(k, 3);
  69727. }
  69728. }
  69729. return Math.max(v, 3);
  69730. };
  69731. /**
  69732. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69733. * @param x The point on the Gaussian distribution to sample.
  69734. * @return the value of the Gaussian function at x.
  69735. */
  69736. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69737. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69738. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69739. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69740. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69741. // truncated at around 1.3% of peak strength.
  69742. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69743. var sigma = (1 / 3);
  69744. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69745. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69746. var weight = (1.0 / denominator) * Math.exp(exponent);
  69747. return weight;
  69748. };
  69749. /**
  69750. * Generates a string that can be used as a floating point number in GLSL.
  69751. * @param x Value to print.
  69752. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69753. * @return GLSL float string.
  69754. */
  69755. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69756. if (decimalFigures === void 0) { decimalFigures = 8; }
  69757. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69758. };
  69759. return BlurPostProcess;
  69760. }(BABYLON.PostProcess));
  69761. BABYLON.BlurPostProcess = BlurPostProcess;
  69762. })(BABYLON || (BABYLON = {}));
  69763. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69764. var BABYLON;
  69765. (function (BABYLON) {
  69766. var Bone = /** @class */ (function (_super) {
  69767. __extends(Bone, _super);
  69768. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69769. if (parentBone === void 0) { parentBone = null; }
  69770. if (localMatrix === void 0) { localMatrix = null; }
  69771. if (restPose === void 0) { restPose = null; }
  69772. if (baseMatrix === void 0) { baseMatrix = null; }
  69773. if (index === void 0) { index = null; }
  69774. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69775. _this.name = name;
  69776. _this.children = new Array();
  69777. _this.animations = new Array();
  69778. // Set this value to map this bone to a different index in the transform matrices.
  69779. // Set this value to -1 to exclude the bone from the transform matrices.
  69780. _this._index = null;
  69781. _this._worldTransform = new BABYLON.Matrix();
  69782. _this._absoluteTransform = new BABYLON.Matrix();
  69783. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69784. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69785. _this._scaleVector = BABYLON.Vector3.One();
  69786. _this._negateScaleChildren = BABYLON.Vector3.One();
  69787. _this._scalingDeterminant = 1;
  69788. _this._skeleton = skeleton;
  69789. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69790. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69791. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69792. _this._index = index;
  69793. skeleton.bones.push(_this);
  69794. _this.setParent(parentBone, false);
  69795. _this._updateDifferenceMatrix();
  69796. return _this;
  69797. }
  69798. Object.defineProperty(Bone.prototype, "_matrix", {
  69799. get: function () {
  69800. return this._localMatrix;
  69801. },
  69802. set: function (val) {
  69803. if (this._localMatrix) {
  69804. this._localMatrix.copyFrom(val);
  69805. }
  69806. else {
  69807. this._localMatrix = val;
  69808. }
  69809. },
  69810. enumerable: true,
  69811. configurable: true
  69812. });
  69813. // Members
  69814. Bone.prototype.getSkeleton = function () {
  69815. return this._skeleton;
  69816. };
  69817. Bone.prototype.getParent = function () {
  69818. return this._parent;
  69819. };
  69820. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69821. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69822. if (this._parent === parent) {
  69823. return;
  69824. }
  69825. if (this._parent) {
  69826. var index = this._parent.children.indexOf(this);
  69827. if (index !== -1) {
  69828. this._parent.children.splice(index, 1);
  69829. }
  69830. }
  69831. this._parent = parent;
  69832. if (this._parent) {
  69833. this._parent.children.push(this);
  69834. }
  69835. if (updateDifferenceMatrix) {
  69836. this._updateDifferenceMatrix();
  69837. }
  69838. };
  69839. Bone.prototype.getLocalMatrix = function () {
  69840. return this._localMatrix;
  69841. };
  69842. Bone.prototype.getBaseMatrix = function () {
  69843. return this._baseMatrix;
  69844. };
  69845. Bone.prototype.getRestPose = function () {
  69846. return this._restPose;
  69847. };
  69848. Bone.prototype.returnToRest = function () {
  69849. this.updateMatrix(this._restPose.clone());
  69850. };
  69851. Bone.prototype.getWorldMatrix = function () {
  69852. return this._worldTransform;
  69853. };
  69854. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69855. return this._invertedAbsoluteTransform;
  69856. };
  69857. Bone.prototype.getAbsoluteTransform = function () {
  69858. return this._absoluteTransform;
  69859. };
  69860. Object.defineProperty(Bone.prototype, "position", {
  69861. // Properties (matches AbstractMesh properties)
  69862. get: function () {
  69863. return this.getPosition();
  69864. },
  69865. set: function (newPosition) {
  69866. this.setPosition(newPosition);
  69867. },
  69868. enumerable: true,
  69869. configurable: true
  69870. });
  69871. Object.defineProperty(Bone.prototype, "rotation", {
  69872. get: function () {
  69873. return this.getRotation();
  69874. },
  69875. set: function (newRotation) {
  69876. this.setRotation(newRotation);
  69877. },
  69878. enumerable: true,
  69879. configurable: true
  69880. });
  69881. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69882. get: function () {
  69883. return this.getRotationQuaternion();
  69884. },
  69885. set: function (newRotation) {
  69886. this.setRotationQuaternion(newRotation);
  69887. },
  69888. enumerable: true,
  69889. configurable: true
  69890. });
  69891. Object.defineProperty(Bone.prototype, "scaling", {
  69892. get: function () {
  69893. return this.getScale();
  69894. },
  69895. set: function (newScaling) {
  69896. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69897. },
  69898. enumerable: true,
  69899. configurable: true
  69900. });
  69901. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  69902. /**
  69903. * Gets the animation properties override
  69904. */
  69905. get: function () {
  69906. return this._skeleton.animationPropertiesOverride;
  69907. },
  69908. enumerable: true,
  69909. configurable: true
  69910. });
  69911. // Methods
  69912. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69913. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69914. this._baseMatrix = matrix.clone();
  69915. this._localMatrix = matrix.clone();
  69916. this._skeleton._markAsDirty();
  69917. if (updateDifferenceMatrix) {
  69918. this._updateDifferenceMatrix();
  69919. }
  69920. };
  69921. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69922. if (!rootMatrix) {
  69923. rootMatrix = this._baseMatrix;
  69924. }
  69925. if (this._parent) {
  69926. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69927. }
  69928. else {
  69929. this._absoluteTransform.copyFrom(rootMatrix);
  69930. }
  69931. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69932. for (var index = 0; index < this.children.length; index++) {
  69933. this.children[index]._updateDifferenceMatrix();
  69934. }
  69935. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69936. };
  69937. Bone.prototype.markAsDirty = function () {
  69938. this._currentRenderId++;
  69939. this._skeleton._markAsDirty();
  69940. };
  69941. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69942. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69943. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69944. // all animation may be coming from a library skeleton, so may need to create animation
  69945. if (this.animations.length === 0) {
  69946. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69947. this.animations[0].setKeys([]);
  69948. }
  69949. // get animation info / verify there is such a range from the source bone
  69950. var sourceRange = source.animations[0].getRange(rangeName);
  69951. if (!sourceRange) {
  69952. return false;
  69953. }
  69954. var from = sourceRange.from;
  69955. var to = sourceRange.to;
  69956. var sourceKeys = source.animations[0].getKeys();
  69957. // rescaling prep
  69958. var sourceBoneLength = source.length;
  69959. var sourceParent = source.getParent();
  69960. var parent = this.getParent();
  69961. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69962. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69963. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69964. var destKeys = this.animations[0].getKeys();
  69965. // loop vars declaration
  69966. var orig;
  69967. var origTranslation;
  69968. var mat;
  69969. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69970. orig = sourceKeys[key];
  69971. if (orig.frame >= from && orig.frame <= to) {
  69972. if (rescaleAsRequired) {
  69973. mat = orig.value.clone();
  69974. // scale based on parent ratio, when bone has parent
  69975. if (parentScalingReqd) {
  69976. origTranslation = mat.getTranslation();
  69977. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69978. // scale based on skeleton dimension ratio when root bone, and value is passed
  69979. }
  69980. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69981. origTranslation = mat.getTranslation();
  69982. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69983. // use original when root bone, and no data for skelDimensionsRatio
  69984. }
  69985. else {
  69986. mat = orig.value;
  69987. }
  69988. }
  69989. else {
  69990. mat = orig.value;
  69991. }
  69992. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69993. }
  69994. }
  69995. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69996. return true;
  69997. };
  69998. /**
  69999. * Translate the bone in local or world space.
  70000. * @param vec The amount to translate the bone.
  70001. * @param space The space that the translation is in.
  70002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70003. */
  70004. Bone.prototype.translate = function (vec, space, mesh) {
  70005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70006. var lm = this.getLocalMatrix();
  70007. if (space == BABYLON.Space.LOCAL) {
  70008. lm.m[12] += vec.x;
  70009. lm.m[13] += vec.y;
  70010. lm.m[14] += vec.z;
  70011. }
  70012. else {
  70013. var wm = null;
  70014. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70015. if (mesh) {
  70016. wm = mesh.getWorldMatrix();
  70017. }
  70018. this._skeleton.computeAbsoluteTransforms();
  70019. var tmat = Bone._tmpMats[0];
  70020. var tvec = Bone._tmpVecs[0];
  70021. if (this._parent) {
  70022. if (mesh && wm) {
  70023. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70024. tmat.multiplyToRef(wm, tmat);
  70025. }
  70026. else {
  70027. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70028. }
  70029. }
  70030. tmat.m[12] = 0;
  70031. tmat.m[13] = 0;
  70032. tmat.m[14] = 0;
  70033. tmat.invert();
  70034. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70035. lm.m[12] += tvec.x;
  70036. lm.m[13] += tvec.y;
  70037. lm.m[14] += tvec.z;
  70038. }
  70039. this.markAsDirty();
  70040. };
  70041. /**
  70042. * Set the postion of the bone in local or world space.
  70043. * @param position The position to set the bone.
  70044. * @param space The space that the position is in.
  70045. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70046. */
  70047. Bone.prototype.setPosition = function (position, space, mesh) {
  70048. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70049. var lm = this.getLocalMatrix();
  70050. if (space == BABYLON.Space.LOCAL) {
  70051. lm.m[12] = position.x;
  70052. lm.m[13] = position.y;
  70053. lm.m[14] = position.z;
  70054. }
  70055. else {
  70056. var wm = null;
  70057. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70058. if (mesh) {
  70059. wm = mesh.getWorldMatrix();
  70060. }
  70061. this._skeleton.computeAbsoluteTransforms();
  70062. var tmat = Bone._tmpMats[0];
  70063. var vec = Bone._tmpVecs[0];
  70064. if (this._parent) {
  70065. if (mesh && wm) {
  70066. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70067. tmat.multiplyToRef(wm, tmat);
  70068. }
  70069. else {
  70070. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70071. }
  70072. }
  70073. tmat.invert();
  70074. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70075. lm.m[12] = vec.x;
  70076. lm.m[13] = vec.y;
  70077. lm.m[14] = vec.z;
  70078. }
  70079. this.markAsDirty();
  70080. };
  70081. /**
  70082. * Set the absolute postion of the bone (world space).
  70083. * @param position The position to set the bone.
  70084. * @param mesh The mesh that this bone is attached to.
  70085. */
  70086. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70087. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70088. };
  70089. /**
  70090. * Set the scale of the bone on the x, y and z axes.
  70091. * @param x The scale of the bone on the x axis.
  70092. * @param x The scale of the bone on the y axis.
  70093. * @param z The scale of the bone on the z axis.
  70094. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70095. */
  70096. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70097. if (scaleChildren === void 0) { scaleChildren = false; }
  70098. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70099. if (!scaleChildren) {
  70100. this._negateScaleChildren.x = 1 / x;
  70101. this._negateScaleChildren.y = 1 / y;
  70102. this._negateScaleChildren.z = 1 / z;
  70103. }
  70104. this._syncScaleVector();
  70105. }
  70106. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70107. };
  70108. /**
  70109. * Scale the bone on the x, y and z axes.
  70110. * @param x The amount to scale the bone on the x axis.
  70111. * @param x The amount to scale the bone on the y axis.
  70112. * @param z The amount to scale the bone on the z axis.
  70113. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70114. */
  70115. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70116. if (scaleChildren === void 0) { scaleChildren = false; }
  70117. var locMat = this.getLocalMatrix();
  70118. var origLocMat = Bone._tmpMats[0];
  70119. origLocMat.copyFrom(locMat);
  70120. var origLocMatInv = Bone._tmpMats[1];
  70121. origLocMatInv.copyFrom(origLocMat);
  70122. origLocMatInv.invert();
  70123. var scaleMat = Bone._tmpMats[2];
  70124. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70125. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70126. this._scaleVector.x *= x;
  70127. this._scaleVector.y *= y;
  70128. this._scaleVector.z *= z;
  70129. locMat.multiplyToRef(origLocMatInv, locMat);
  70130. locMat.multiplyToRef(scaleMat, locMat);
  70131. locMat.multiplyToRef(origLocMat, locMat);
  70132. var parent = this.getParent();
  70133. if (parent) {
  70134. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70135. }
  70136. else {
  70137. this.getAbsoluteTransform().copyFrom(locMat);
  70138. }
  70139. var len = this.children.length;
  70140. scaleMat.invert();
  70141. for (var i = 0; i < len; i++) {
  70142. var child = this.children[i];
  70143. var cm = child.getLocalMatrix();
  70144. cm.multiplyToRef(scaleMat, cm);
  70145. var lm = child.getLocalMatrix();
  70146. lm.m[12] *= x;
  70147. lm.m[13] *= y;
  70148. lm.m[14] *= z;
  70149. }
  70150. this.computeAbsoluteTransforms();
  70151. if (scaleChildren) {
  70152. for (var i = 0; i < len; i++) {
  70153. this.children[i].scale(x, y, z, scaleChildren);
  70154. }
  70155. }
  70156. this.markAsDirty();
  70157. };
  70158. /**
  70159. * Set the yaw, pitch, and roll of the bone in local or world space.
  70160. * @param yaw The rotation of the bone on the y axis.
  70161. * @param pitch The rotation of the bone on the x axis.
  70162. * @param roll The rotation of the bone on the z axis.
  70163. * @param space The space that the axes of rotation are in.
  70164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70165. */
  70166. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70168. var rotMat = Bone._tmpMats[0];
  70169. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70170. var rotMatInv = Bone._tmpMats[1];
  70171. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70172. rotMatInv.multiplyToRef(rotMat, rotMat);
  70173. this._rotateWithMatrix(rotMat, space, mesh);
  70174. };
  70175. /**
  70176. * Rotate the bone on an axis in local or world space.
  70177. * @param axis The axis to rotate the bone on.
  70178. * @param amount The amount to rotate the bone.
  70179. * @param space The space that the axis is in.
  70180. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70181. */
  70182. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70183. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70184. var rmat = Bone._tmpMats[0];
  70185. rmat.m[12] = 0;
  70186. rmat.m[13] = 0;
  70187. rmat.m[14] = 0;
  70188. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70189. this._rotateWithMatrix(rmat, space, mesh);
  70190. };
  70191. /**
  70192. * Set the rotation of the bone to a particular axis angle in local or world space.
  70193. * @param axis The axis to rotate the bone on.
  70194. * @param angle The angle that the bone should be rotated to.
  70195. * @param space The space that the axis is in.
  70196. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70197. */
  70198. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70200. var rotMat = Bone._tmpMats[0];
  70201. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70202. var rotMatInv = Bone._tmpMats[1];
  70203. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70204. rotMatInv.multiplyToRef(rotMat, rotMat);
  70205. this._rotateWithMatrix(rotMat, space, mesh);
  70206. };
  70207. /**
  70208. * Set the euler rotation of the bone in local of world space.
  70209. * @param rotation The euler rotation that the bone should be set to.
  70210. * @param space The space that the rotation is in.
  70211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70212. */
  70213. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70215. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70216. };
  70217. /**
  70218. * Set the quaternion rotation of the bone in local of world space.
  70219. * @param quat The quaternion rotation that the bone should be set to.
  70220. * @param space The space that the rotation is in.
  70221. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70222. */
  70223. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70224. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70225. var rotMatInv = Bone._tmpMats[0];
  70226. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70227. var rotMat = Bone._tmpMats[1];
  70228. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70229. rotMatInv.multiplyToRef(rotMat, rotMat);
  70230. this._rotateWithMatrix(rotMat, space, mesh);
  70231. };
  70232. /**
  70233. * Set the rotation matrix of the bone in local of world space.
  70234. * @param rotMat The rotation matrix that the bone should be set to.
  70235. * @param space The space that the rotation is in.
  70236. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70237. */
  70238. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70239. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70240. var rotMatInv = Bone._tmpMats[0];
  70241. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70242. var rotMat2 = Bone._tmpMats[1];
  70243. rotMat2.copyFrom(rotMat);
  70244. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70245. this._rotateWithMatrix(rotMat2, space, mesh);
  70246. };
  70247. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70249. var lmat = this.getLocalMatrix();
  70250. var lx = lmat.m[12];
  70251. var ly = lmat.m[13];
  70252. var lz = lmat.m[14];
  70253. var parent = this.getParent();
  70254. var parentScale = Bone._tmpMats[3];
  70255. var parentScaleInv = Bone._tmpMats[4];
  70256. if (parent) {
  70257. if (space == BABYLON.Space.WORLD) {
  70258. if (mesh) {
  70259. parentScale.copyFrom(mesh.getWorldMatrix());
  70260. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70261. }
  70262. else {
  70263. parentScale.copyFrom(parent.getAbsoluteTransform());
  70264. }
  70265. }
  70266. else {
  70267. parentScale = parent._scaleMatrix;
  70268. }
  70269. parentScaleInv.copyFrom(parentScale);
  70270. parentScaleInv.invert();
  70271. lmat.multiplyToRef(parentScale, lmat);
  70272. lmat.multiplyToRef(rmat, lmat);
  70273. lmat.multiplyToRef(parentScaleInv, lmat);
  70274. }
  70275. else {
  70276. if (space == BABYLON.Space.WORLD && mesh) {
  70277. parentScale.copyFrom(mesh.getWorldMatrix());
  70278. parentScaleInv.copyFrom(parentScale);
  70279. parentScaleInv.invert();
  70280. lmat.multiplyToRef(parentScale, lmat);
  70281. lmat.multiplyToRef(rmat, lmat);
  70282. lmat.multiplyToRef(parentScaleInv, lmat);
  70283. }
  70284. else {
  70285. lmat.multiplyToRef(rmat, lmat);
  70286. }
  70287. }
  70288. lmat.m[12] = lx;
  70289. lmat.m[13] = ly;
  70290. lmat.m[14] = lz;
  70291. this.computeAbsoluteTransforms();
  70292. this.markAsDirty();
  70293. };
  70294. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70296. if (space == BABYLON.Space.WORLD) {
  70297. var scaleMatrix = Bone._tmpMats[2];
  70298. scaleMatrix.copyFrom(this._scaleMatrix);
  70299. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70300. if (mesh) {
  70301. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70302. var meshScale = Bone._tmpMats[3];
  70303. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70304. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70305. }
  70306. rotMatInv.invert();
  70307. scaleMatrix.m[0] *= this._scalingDeterminant;
  70308. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70309. }
  70310. else {
  70311. rotMatInv.copyFrom(this.getLocalMatrix());
  70312. rotMatInv.invert();
  70313. var scaleMatrix = Bone._tmpMats[2];
  70314. scaleMatrix.copyFrom(this._scaleMatrix);
  70315. if (this._parent) {
  70316. var pscaleMatrix = Bone._tmpMats[3];
  70317. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70318. pscaleMatrix.invert();
  70319. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70320. }
  70321. else {
  70322. scaleMatrix.m[0] *= this._scalingDeterminant;
  70323. }
  70324. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70325. }
  70326. };
  70327. /**
  70328. * Get the scale of the bone
  70329. * @returns the scale of the bone
  70330. */
  70331. Bone.prototype.getScale = function () {
  70332. return this._scaleVector.clone();
  70333. };
  70334. /**
  70335. * Copy the scale of the bone to a vector3.
  70336. * @param result The vector3 to copy the scale to
  70337. */
  70338. Bone.prototype.getScaleToRef = function (result) {
  70339. result.copyFrom(this._scaleVector);
  70340. };
  70341. /**
  70342. * Get the position of the bone in local or world space.
  70343. * @param space The space that the returned position is in.
  70344. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70345. * @returns The position of the bone
  70346. */
  70347. Bone.prototype.getPosition = function (space, mesh) {
  70348. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70349. if (mesh === void 0) { mesh = null; }
  70350. var pos = BABYLON.Vector3.Zero();
  70351. this.getPositionToRef(space, mesh, pos);
  70352. return pos;
  70353. };
  70354. /**
  70355. * Copy the position of the bone to a vector3 in local or world space.
  70356. * @param space The space that the returned position is in.
  70357. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70358. * @param result The vector3 to copy the position to.
  70359. */
  70360. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70362. if (space == BABYLON.Space.LOCAL) {
  70363. var lm = this.getLocalMatrix();
  70364. result.x = lm.m[12];
  70365. result.y = lm.m[13];
  70366. result.z = lm.m[14];
  70367. }
  70368. else {
  70369. var wm = null;
  70370. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70371. if (mesh) {
  70372. wm = mesh.getWorldMatrix();
  70373. }
  70374. this._skeleton.computeAbsoluteTransforms();
  70375. var tmat = Bone._tmpMats[0];
  70376. if (mesh && wm) {
  70377. tmat.copyFrom(this.getAbsoluteTransform());
  70378. tmat.multiplyToRef(wm, tmat);
  70379. }
  70380. else {
  70381. tmat = this.getAbsoluteTransform();
  70382. }
  70383. result.x = tmat.m[12];
  70384. result.y = tmat.m[13];
  70385. result.z = tmat.m[14];
  70386. }
  70387. };
  70388. /**
  70389. * Get the absolute position of the bone (world space).
  70390. * @param mesh The mesh that this bone is attached to.
  70391. * @returns The absolute position of the bone
  70392. */
  70393. Bone.prototype.getAbsolutePosition = function (mesh) {
  70394. if (mesh === void 0) { mesh = null; }
  70395. var pos = BABYLON.Vector3.Zero();
  70396. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70397. return pos;
  70398. };
  70399. /**
  70400. * Copy the absolute position of the bone (world space) to the result param.
  70401. * @param mesh The mesh that this bone is attached to.
  70402. * @param result The vector3 to copy the absolute position to.
  70403. */
  70404. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70405. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70406. };
  70407. /**
  70408. * Compute the absolute transforms of this bone and its children.
  70409. */
  70410. Bone.prototype.computeAbsoluteTransforms = function () {
  70411. if (this._parent) {
  70412. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70413. }
  70414. else {
  70415. this._absoluteTransform.copyFrom(this._localMatrix);
  70416. var poseMatrix = this._skeleton.getPoseMatrix();
  70417. if (poseMatrix) {
  70418. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70419. }
  70420. }
  70421. var children = this.children;
  70422. var len = children.length;
  70423. for (var i = 0; i < len; i++) {
  70424. children[i].computeAbsoluteTransforms();
  70425. }
  70426. };
  70427. Bone.prototype._syncScaleVector = function () {
  70428. var lm = this.getLocalMatrix();
  70429. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70430. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70431. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70432. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70433. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70434. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70435. this._scaleVector.x = xs * Math.sqrt(xsq);
  70436. this._scaleVector.y = ys * Math.sqrt(ysq);
  70437. this._scaleVector.z = zs * Math.sqrt(zsq);
  70438. if (this._parent) {
  70439. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70440. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70441. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70442. }
  70443. 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);
  70444. };
  70445. /**
  70446. * Get the world direction from an axis that is in the local space of the bone.
  70447. * @param localAxis The local direction that is used to compute the world direction.
  70448. * @param mesh The mesh that this bone is attached to.
  70449. * @returns The world direction
  70450. */
  70451. Bone.prototype.getDirection = function (localAxis, mesh) {
  70452. if (mesh === void 0) { mesh = null; }
  70453. var result = BABYLON.Vector3.Zero();
  70454. this.getDirectionToRef(localAxis, mesh, result);
  70455. return result;
  70456. };
  70457. /**
  70458. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70459. * @param localAxis The local direction that is used to compute the world direction.
  70460. * @param mesh The mesh that this bone is attached to.
  70461. * @param result The vector3 that the world direction will be copied to.
  70462. */
  70463. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70464. if (mesh === void 0) { mesh = null; }
  70465. var wm = null;
  70466. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70467. if (mesh) {
  70468. wm = mesh.getWorldMatrix();
  70469. }
  70470. this._skeleton.computeAbsoluteTransforms();
  70471. var mat = Bone._tmpMats[0];
  70472. mat.copyFrom(this.getAbsoluteTransform());
  70473. if (mesh && wm) {
  70474. mat.multiplyToRef(wm, mat);
  70475. }
  70476. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70477. result.normalize();
  70478. };
  70479. /**
  70480. * Get the euler rotation of the bone in local or world space.
  70481. * @param space The space that the rotation should be in.
  70482. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70483. * @returns The euler rotation
  70484. */
  70485. Bone.prototype.getRotation = function (space, mesh) {
  70486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70487. if (mesh === void 0) { mesh = null; }
  70488. var result = BABYLON.Vector3.Zero();
  70489. this.getRotationToRef(space, mesh, result);
  70490. return result;
  70491. };
  70492. /**
  70493. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70494. * @param space The space that the rotation should be in.
  70495. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70496. * @param result The vector3 that the rotation should be copied to.
  70497. */
  70498. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70500. if (mesh === void 0) { mesh = null; }
  70501. var quat = Bone._tmpQuat;
  70502. this.getRotationQuaternionToRef(space, mesh, quat);
  70503. quat.toEulerAnglesToRef(result);
  70504. };
  70505. /**
  70506. * Get the quaternion rotation of the bone in either local or world space.
  70507. * @param space The space that the rotation should be in.
  70508. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70509. * @returns The quaternion rotation
  70510. */
  70511. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70512. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70513. if (mesh === void 0) { mesh = null; }
  70514. var result = BABYLON.Quaternion.Identity();
  70515. this.getRotationQuaternionToRef(space, mesh, result);
  70516. return result;
  70517. };
  70518. /**
  70519. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70520. * @param space The space that the rotation should be in.
  70521. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70522. * @param result The quaternion that the rotation should be copied to.
  70523. */
  70524. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70525. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70526. if (mesh === void 0) { mesh = null; }
  70527. if (space == BABYLON.Space.LOCAL) {
  70528. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70529. }
  70530. else {
  70531. var mat = Bone._tmpMats[0];
  70532. var amat = this.getAbsoluteTransform();
  70533. if (mesh) {
  70534. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70535. }
  70536. else {
  70537. mat.copyFrom(amat);
  70538. }
  70539. mat.m[0] *= this._scalingDeterminant;
  70540. mat.m[1] *= this._scalingDeterminant;
  70541. mat.m[2] *= this._scalingDeterminant;
  70542. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70543. }
  70544. };
  70545. /**
  70546. * Get the rotation matrix of the bone in local or world space.
  70547. * @param space The space that the rotation should be in.
  70548. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70549. * @returns The rotation matrix
  70550. */
  70551. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70552. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70553. var result = BABYLON.Matrix.Identity();
  70554. this.getRotationMatrixToRef(space, mesh, result);
  70555. return result;
  70556. };
  70557. /**
  70558. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70559. * @param space The space that the rotation should be in.
  70560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70561. * @param result The quaternion that the rotation should be copied to.
  70562. */
  70563. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70565. if (space == BABYLON.Space.LOCAL) {
  70566. this.getLocalMatrix().getRotationMatrixToRef(result);
  70567. }
  70568. else {
  70569. var mat = Bone._tmpMats[0];
  70570. var amat = this.getAbsoluteTransform();
  70571. if (mesh) {
  70572. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70573. }
  70574. else {
  70575. mat.copyFrom(amat);
  70576. }
  70577. mat.m[0] *= this._scalingDeterminant;
  70578. mat.m[1] *= this._scalingDeterminant;
  70579. mat.m[2] *= this._scalingDeterminant;
  70580. mat.getRotationMatrixToRef(result);
  70581. }
  70582. };
  70583. /**
  70584. * Get the world position of a point that is in the local space of the bone.
  70585. * @param position The local position
  70586. * @param mesh The mesh that this bone is attached to.
  70587. * @returns The world position
  70588. */
  70589. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70590. if (mesh === void 0) { mesh = null; }
  70591. var result = BABYLON.Vector3.Zero();
  70592. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70593. return result;
  70594. };
  70595. /**
  70596. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70597. * @param position The local position
  70598. * @param mesh The mesh that this bone is attached to.
  70599. * @param result The vector3 that the world position should be copied to.
  70600. */
  70601. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70602. if (mesh === void 0) { mesh = null; }
  70603. var wm = null;
  70604. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70605. if (mesh) {
  70606. wm = mesh.getWorldMatrix();
  70607. }
  70608. this._skeleton.computeAbsoluteTransforms();
  70609. var tmat = Bone._tmpMats[0];
  70610. if (mesh && wm) {
  70611. tmat.copyFrom(this.getAbsoluteTransform());
  70612. tmat.multiplyToRef(wm, tmat);
  70613. }
  70614. else {
  70615. tmat = this.getAbsoluteTransform();
  70616. }
  70617. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70618. };
  70619. /**
  70620. * Get the local position of a point that is in world space.
  70621. * @param position The world position
  70622. * @param mesh The mesh that this bone is attached to.
  70623. * @returns The local position
  70624. */
  70625. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70626. if (mesh === void 0) { mesh = null; }
  70627. var result = BABYLON.Vector3.Zero();
  70628. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70629. return result;
  70630. };
  70631. /**
  70632. * Get the local position of a point that is in world space and copy it to the result param.
  70633. * @param position The world position
  70634. * @param mesh The mesh that this bone is attached to.
  70635. * @param result The vector3 that the local position should be copied to.
  70636. */
  70637. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70638. if (mesh === void 0) { mesh = null; }
  70639. var wm = null;
  70640. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70641. if (mesh) {
  70642. wm = mesh.getWorldMatrix();
  70643. }
  70644. this._skeleton.computeAbsoluteTransforms();
  70645. var tmat = Bone._tmpMats[0];
  70646. tmat.copyFrom(this.getAbsoluteTransform());
  70647. if (mesh && wm) {
  70648. tmat.multiplyToRef(wm, tmat);
  70649. }
  70650. tmat.invert();
  70651. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70652. };
  70653. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70654. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70655. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70656. return Bone;
  70657. }(BABYLON.Node));
  70658. BABYLON.Bone = Bone;
  70659. })(BABYLON || (BABYLON = {}));
  70660. //# sourceMappingURL=babylon.bone.js.map
  70661. var BABYLON;
  70662. (function (BABYLON) {
  70663. var BoneIKController = /** @class */ (function () {
  70664. function BoneIKController(mesh, bone, options) {
  70665. this.targetPosition = BABYLON.Vector3.Zero();
  70666. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70667. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70668. this.poleAngle = 0;
  70669. this.slerpAmount = 1;
  70670. this._bone1Quat = BABYLON.Quaternion.Identity();
  70671. this._bone1Mat = BABYLON.Matrix.Identity();
  70672. this._bone2Ang = Math.PI;
  70673. this._maxAngle = Math.PI;
  70674. this._rightHandedSystem = false;
  70675. this._bendAxis = BABYLON.Vector3.Right();
  70676. this._slerping = false;
  70677. this._adjustRoll = 0;
  70678. this._bone2 = bone;
  70679. this._bone1 = bone.getParent();
  70680. if (!this._bone1) {
  70681. return;
  70682. }
  70683. this.mesh = mesh;
  70684. var bonePos = bone.getPosition();
  70685. if (bone.getAbsoluteTransform().determinant() > 0) {
  70686. this._rightHandedSystem = true;
  70687. this._bendAxis.x = 0;
  70688. this._bendAxis.y = 0;
  70689. this._bendAxis.z = -1;
  70690. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70691. this._adjustRoll = Math.PI * .5;
  70692. this._bendAxis.z = 1;
  70693. }
  70694. }
  70695. if (this._bone1.length) {
  70696. var boneScale1 = this._bone1.getScale();
  70697. var boneScale2 = this._bone2.getScale();
  70698. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70699. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70700. }
  70701. else if (this._bone1.children[0]) {
  70702. mesh.computeWorldMatrix(true);
  70703. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70704. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70705. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70706. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70707. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70708. }
  70709. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70710. this.maxAngle = Math.PI;
  70711. if (options) {
  70712. if (options.targetMesh) {
  70713. this.targetMesh = options.targetMesh;
  70714. this.targetMesh.computeWorldMatrix(true);
  70715. }
  70716. if (options.poleTargetMesh) {
  70717. this.poleTargetMesh = options.poleTargetMesh;
  70718. this.poleTargetMesh.computeWorldMatrix(true);
  70719. }
  70720. else if (options.poleTargetBone) {
  70721. this.poleTargetBone = options.poleTargetBone;
  70722. }
  70723. else if (this._bone1.getParent()) {
  70724. this.poleTargetBone = this._bone1.getParent();
  70725. }
  70726. if (options.poleTargetLocalOffset) {
  70727. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70728. }
  70729. if (options.poleAngle) {
  70730. this.poleAngle = options.poleAngle;
  70731. }
  70732. if (options.bendAxis) {
  70733. this._bendAxis.copyFrom(options.bendAxis);
  70734. }
  70735. if (options.maxAngle) {
  70736. this.maxAngle = options.maxAngle;
  70737. }
  70738. if (options.slerpAmount) {
  70739. this.slerpAmount = options.slerpAmount;
  70740. }
  70741. }
  70742. }
  70743. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70744. get: function () {
  70745. return this._maxAngle;
  70746. },
  70747. set: function (value) {
  70748. this._setMaxAngle(value);
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. BoneIKController.prototype._setMaxAngle = function (ang) {
  70754. if (ang < 0) {
  70755. ang = 0;
  70756. }
  70757. if (ang > Math.PI || ang == undefined) {
  70758. ang = Math.PI;
  70759. }
  70760. this._maxAngle = ang;
  70761. var a = this._bone1Length;
  70762. var b = this._bone2Length;
  70763. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70764. };
  70765. BoneIKController.prototype.update = function () {
  70766. var bone1 = this._bone1;
  70767. if (!bone1) {
  70768. return;
  70769. }
  70770. var target = this.targetPosition;
  70771. var poleTarget = this.poleTargetPosition;
  70772. var mat1 = BoneIKController._tmpMats[0];
  70773. var mat2 = BoneIKController._tmpMats[1];
  70774. if (this.targetMesh) {
  70775. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70776. }
  70777. if (this.poleTargetBone) {
  70778. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70779. }
  70780. else if (this.poleTargetMesh) {
  70781. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70782. }
  70783. var bonePos = BoneIKController._tmpVecs[0];
  70784. var zaxis = BoneIKController._tmpVecs[1];
  70785. var xaxis = BoneIKController._tmpVecs[2];
  70786. var yaxis = BoneIKController._tmpVecs[3];
  70787. var upAxis = BoneIKController._tmpVecs[4];
  70788. var _tmpQuat = BoneIKController._tmpQuat;
  70789. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70790. poleTarget.subtractToRef(bonePos, upAxis);
  70791. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70792. upAxis.y = 1;
  70793. }
  70794. else {
  70795. upAxis.normalize();
  70796. }
  70797. target.subtractToRef(bonePos, yaxis);
  70798. yaxis.normalize();
  70799. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70800. zaxis.normalize();
  70801. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70802. xaxis.normalize();
  70803. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70804. var a = this._bone1Length;
  70805. var b = this._bone2Length;
  70806. var c = BABYLON.Vector3.Distance(bonePos, target);
  70807. if (this._maxReach > 0) {
  70808. c = Math.min(this._maxReach, c);
  70809. }
  70810. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70811. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70812. if (acosa > 1) {
  70813. acosa = 1;
  70814. }
  70815. if (acosb > 1) {
  70816. acosb = 1;
  70817. }
  70818. if (acosa < -1) {
  70819. acosa = -1;
  70820. }
  70821. if (acosb < -1) {
  70822. acosb = -1;
  70823. }
  70824. var angA = Math.acos(acosa);
  70825. var angB = Math.acos(acosb);
  70826. var angC = -angA - angB;
  70827. if (this._rightHandedSystem) {
  70828. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70829. mat2.multiplyToRef(mat1, mat1);
  70830. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70831. mat2.multiplyToRef(mat1, mat1);
  70832. }
  70833. else {
  70834. var _tmpVec = BoneIKController._tmpVecs[5];
  70835. _tmpVec.copyFrom(this._bendAxis);
  70836. _tmpVec.x *= -1;
  70837. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70838. mat2.multiplyToRef(mat1, mat1);
  70839. }
  70840. if (this.poleAngle) {
  70841. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70842. mat1.multiplyToRef(mat2, mat1);
  70843. }
  70844. if (this._bone1) {
  70845. if (this.slerpAmount < 1) {
  70846. if (!this._slerping) {
  70847. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70848. }
  70849. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70850. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70851. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70852. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70853. this._slerping = true;
  70854. }
  70855. else {
  70856. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70857. this._bone1Mat.copyFrom(mat1);
  70858. this._slerping = false;
  70859. }
  70860. }
  70861. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70862. this._bone2Ang = angC;
  70863. };
  70864. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70865. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70866. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70867. return BoneIKController;
  70868. }());
  70869. BABYLON.BoneIKController = BoneIKController;
  70870. })(BABYLON || (BABYLON = {}));
  70871. //# sourceMappingURL=babylon.boneIKController.js.map
  70872. var BABYLON;
  70873. (function (BABYLON) {
  70874. var BoneLookController = /** @class */ (function () {
  70875. /**
  70876. * Create a BoneLookController
  70877. * @param mesh the mesh that the bone belongs to
  70878. * @param bone the bone that will be looking to the target
  70879. * @param target the target Vector3 to look at
  70880. * @param settings optional settings:
  70881. * - maxYaw: the maximum angle the bone will yaw to
  70882. * - minYaw: the minimum angle the bone will yaw to
  70883. * - maxPitch: the maximum angle the bone will pitch to
  70884. * - minPitch: the minimum angle the bone will yaw to
  70885. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70886. * - upAxis: the up axis of the coordinate system
  70887. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70888. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70889. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70890. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70891. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70892. * - adjustRoll: used to make an adjustment to the roll of the bone
  70893. **/
  70894. function BoneLookController(mesh, bone, target, options) {
  70895. /**
  70896. * The up axis of the coordinate system that is used when the bone is rotated.
  70897. */
  70898. this.upAxis = BABYLON.Vector3.Up();
  70899. /**
  70900. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70901. */
  70902. this.upAxisSpace = BABYLON.Space.LOCAL;
  70903. /**
  70904. * Used to make an adjustment to the yaw of the bone.
  70905. */
  70906. this.adjustYaw = 0;
  70907. /**
  70908. * Used to make an adjustment to the pitch of the bone.
  70909. */
  70910. this.adjustPitch = 0;
  70911. /**
  70912. * Used to make an adjustment to the roll of the bone.
  70913. */
  70914. this.adjustRoll = 0;
  70915. /**
  70916. * 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).
  70917. */
  70918. this.slerpAmount = 1;
  70919. this._boneQuat = BABYLON.Quaternion.Identity();
  70920. this._slerping = false;
  70921. this._firstFrameSkipped = false;
  70922. this._fowardAxis = BABYLON.Vector3.Forward();
  70923. this.mesh = mesh;
  70924. this.bone = bone;
  70925. this.target = target;
  70926. if (options) {
  70927. if (options.adjustYaw) {
  70928. this.adjustYaw = options.adjustYaw;
  70929. }
  70930. if (options.adjustPitch) {
  70931. this.adjustPitch = options.adjustPitch;
  70932. }
  70933. if (options.adjustRoll) {
  70934. this.adjustRoll = options.adjustRoll;
  70935. }
  70936. if (options.maxYaw != null) {
  70937. this.maxYaw = options.maxYaw;
  70938. }
  70939. else {
  70940. this.maxYaw = Math.PI;
  70941. }
  70942. if (options.minYaw != null) {
  70943. this.minYaw = options.minYaw;
  70944. }
  70945. else {
  70946. this.minYaw = -Math.PI;
  70947. }
  70948. if (options.maxPitch != null) {
  70949. this.maxPitch = options.maxPitch;
  70950. }
  70951. else {
  70952. this.maxPitch = Math.PI;
  70953. }
  70954. if (options.minPitch != null) {
  70955. this.minPitch = options.minPitch;
  70956. }
  70957. else {
  70958. this.minPitch = -Math.PI;
  70959. }
  70960. if (options.slerpAmount != null) {
  70961. this.slerpAmount = options.slerpAmount;
  70962. }
  70963. if (options.upAxis != null) {
  70964. this.upAxis = options.upAxis;
  70965. }
  70966. if (options.upAxisSpace != null) {
  70967. this.upAxisSpace = options.upAxisSpace;
  70968. }
  70969. if (options.yawAxis != null || options.pitchAxis != null) {
  70970. var newYawAxis = BABYLON.Axis.Y;
  70971. var newPitchAxis = BABYLON.Axis.X;
  70972. if (options.yawAxis != null) {
  70973. newYawAxis = options.yawAxis.clone();
  70974. newYawAxis.normalize();
  70975. }
  70976. if (options.pitchAxis != null) {
  70977. newPitchAxis = options.pitchAxis.clone();
  70978. newPitchAxis.normalize();
  70979. }
  70980. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70981. this._transformYawPitch = BABYLON.Matrix.Identity();
  70982. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70983. this._transformYawPitchInv = this._transformYawPitch.clone();
  70984. this._transformYawPitch.invert();
  70985. }
  70986. }
  70987. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70988. this.upAxisSpace = BABYLON.Space.LOCAL;
  70989. }
  70990. }
  70991. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70992. /**
  70993. * Get/set the minimum yaw angle that the bone can look to.
  70994. */
  70995. get: function () {
  70996. return this._minYaw;
  70997. },
  70998. set: function (value) {
  70999. this._minYaw = value;
  71000. this._minYawSin = Math.sin(value);
  71001. this._minYawCos = Math.cos(value);
  71002. if (this._maxYaw != null) {
  71003. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71004. this._yawRange = this._maxYaw - this._minYaw;
  71005. }
  71006. },
  71007. enumerable: true,
  71008. configurable: true
  71009. });
  71010. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71011. /**
  71012. * Get/set the maximum yaw angle that the bone can look to.
  71013. */
  71014. get: function () {
  71015. return this._maxYaw;
  71016. },
  71017. set: function (value) {
  71018. this._maxYaw = value;
  71019. this._maxYawSin = Math.sin(value);
  71020. this._maxYawCos = Math.cos(value);
  71021. if (this._minYaw != null) {
  71022. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71023. this._yawRange = this._maxYaw - this._minYaw;
  71024. }
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71030. /**
  71031. * Get/set the minimum pitch angle that the bone can look to.
  71032. */
  71033. get: function () {
  71034. return this._minPitch;
  71035. },
  71036. set: function (value) {
  71037. this._minPitch = value;
  71038. this._minPitchTan = Math.tan(value);
  71039. },
  71040. enumerable: true,
  71041. configurable: true
  71042. });
  71043. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71044. /**
  71045. * Get/set the maximum pitch angle that the bone can look to.
  71046. */
  71047. get: function () {
  71048. return this._maxPitch;
  71049. },
  71050. set: function (value) {
  71051. this._maxPitch = value;
  71052. this._maxPitchTan = Math.tan(value);
  71053. },
  71054. enumerable: true,
  71055. configurable: true
  71056. });
  71057. /**
  71058. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71059. */
  71060. BoneLookController.prototype.update = function () {
  71061. //skip the first frame when slerping so that the mesh rotation is correct
  71062. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71063. this._firstFrameSkipped = true;
  71064. return;
  71065. }
  71066. var bone = this.bone;
  71067. var bonePos = BoneLookController._tmpVecs[0];
  71068. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71069. var target = this.target;
  71070. var _tmpMat1 = BoneLookController._tmpMats[0];
  71071. var _tmpMat2 = BoneLookController._tmpMats[1];
  71072. var mesh = this.mesh;
  71073. var parentBone = bone.getParent();
  71074. var upAxis = BoneLookController._tmpVecs[1];
  71075. upAxis.copyFrom(this.upAxis);
  71076. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71077. if (this._transformYawPitch) {
  71078. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71079. }
  71080. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71081. }
  71082. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71083. mesh.getDirectionToRef(upAxis, upAxis);
  71084. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71085. upAxis.normalize();
  71086. }
  71087. }
  71088. var checkYaw = false;
  71089. var checkPitch = false;
  71090. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71091. checkYaw = true;
  71092. }
  71093. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71094. checkPitch = true;
  71095. }
  71096. if (checkYaw || checkPitch) {
  71097. var spaceMat = BoneLookController._tmpMats[2];
  71098. var spaceMatInv = BoneLookController._tmpMats[3];
  71099. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71100. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71101. }
  71102. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71103. spaceMat.copyFrom(mesh.getWorldMatrix());
  71104. }
  71105. else {
  71106. var forwardAxis = BoneLookController._tmpVecs[2];
  71107. forwardAxis.copyFrom(this._fowardAxis);
  71108. if (this._transformYawPitch) {
  71109. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71110. }
  71111. if (parentBone) {
  71112. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71113. }
  71114. else {
  71115. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71116. }
  71117. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71118. rightAxis.normalize();
  71119. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71120. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71121. }
  71122. spaceMat.invertToRef(spaceMatInv);
  71123. var xzlen = null;
  71124. if (checkPitch) {
  71125. var localTarget = BoneLookController._tmpVecs[3];
  71126. target.subtractToRef(bonePos, localTarget);
  71127. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71128. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71129. var pitch = Math.atan2(localTarget.y, xzlen);
  71130. var newPitch = pitch;
  71131. if (pitch > this._maxPitch) {
  71132. localTarget.y = this._maxPitchTan * xzlen;
  71133. newPitch = this._maxPitch;
  71134. }
  71135. else if (pitch < this._minPitch) {
  71136. localTarget.y = this._minPitchTan * xzlen;
  71137. newPitch = this._minPitch;
  71138. }
  71139. if (pitch != newPitch) {
  71140. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71141. localTarget.addInPlace(bonePos);
  71142. target = localTarget;
  71143. }
  71144. }
  71145. if (checkYaw) {
  71146. var localTarget = BoneLookController._tmpVecs[4];
  71147. target.subtractToRef(bonePos, localTarget);
  71148. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71149. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71150. var newYaw = yaw;
  71151. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71152. if (xzlen == null) {
  71153. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71154. }
  71155. if (this._yawRange > Math.PI) {
  71156. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71157. localTarget.z = this._maxYawCos * xzlen;
  71158. localTarget.x = this._maxYawSin * xzlen;
  71159. newYaw = this._maxYaw;
  71160. }
  71161. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71162. localTarget.z = this._minYawCos * xzlen;
  71163. localTarget.x = this._minYawSin * xzlen;
  71164. newYaw = this._minYaw;
  71165. }
  71166. }
  71167. else {
  71168. if (yaw > this._maxYaw) {
  71169. localTarget.z = this._maxYawCos * xzlen;
  71170. localTarget.x = this._maxYawSin * xzlen;
  71171. newYaw = this._maxYaw;
  71172. }
  71173. else if (yaw < this._minYaw) {
  71174. localTarget.z = this._minYawCos * xzlen;
  71175. localTarget.x = this._minYawSin * xzlen;
  71176. newYaw = this._minYaw;
  71177. }
  71178. }
  71179. }
  71180. if (this._slerping && this._yawRange > Math.PI) {
  71181. //are we going to be crossing into the min/max region?
  71182. var boneFwd = BoneLookController._tmpVecs[8];
  71183. boneFwd.copyFrom(BABYLON.Axis.Z);
  71184. if (this._transformYawPitch) {
  71185. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71186. }
  71187. var boneRotMat = BoneLookController._tmpMats[4];
  71188. this._boneQuat.toRotationMatrix(boneRotMat);
  71189. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71190. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71191. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71192. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71193. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71194. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71195. if (angBtwTar > angBtwMidYaw) {
  71196. if (xzlen == null) {
  71197. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71198. }
  71199. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71200. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71201. if (angBtwMin < angBtwMax) {
  71202. newYaw = boneYaw + Math.PI * .75;
  71203. localTarget.z = Math.cos(newYaw) * xzlen;
  71204. localTarget.x = Math.sin(newYaw) * xzlen;
  71205. }
  71206. else {
  71207. newYaw = boneYaw - Math.PI * .75;
  71208. localTarget.z = Math.cos(newYaw) * xzlen;
  71209. localTarget.x = Math.sin(newYaw) * xzlen;
  71210. }
  71211. }
  71212. }
  71213. if (yaw != newYaw) {
  71214. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71215. localTarget.addInPlace(bonePos);
  71216. target = localTarget;
  71217. }
  71218. }
  71219. }
  71220. var zaxis = BoneLookController._tmpVecs[5];
  71221. var xaxis = BoneLookController._tmpVecs[6];
  71222. var yaxis = BoneLookController._tmpVecs[7];
  71223. var _tmpQuat = BoneLookController._tmpQuat;
  71224. target.subtractToRef(bonePos, zaxis);
  71225. zaxis.normalize();
  71226. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71227. xaxis.normalize();
  71228. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71229. yaxis.normalize();
  71230. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71231. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71232. return;
  71233. }
  71234. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71235. return;
  71236. }
  71237. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71238. return;
  71239. }
  71240. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71241. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71242. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71243. }
  71244. if (this.slerpAmount < 1) {
  71245. if (!this._slerping) {
  71246. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71247. }
  71248. if (this._transformYawPitch) {
  71249. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71250. }
  71251. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71252. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71253. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71254. this._slerping = true;
  71255. }
  71256. else {
  71257. if (this._transformYawPitch) {
  71258. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71259. }
  71260. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71261. this._slerping = false;
  71262. }
  71263. };
  71264. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71265. var angDiff = ang2 - ang1;
  71266. angDiff %= Math.PI * 2;
  71267. if (angDiff > Math.PI) {
  71268. angDiff -= Math.PI * 2;
  71269. }
  71270. else if (angDiff < -Math.PI) {
  71271. angDiff += Math.PI * 2;
  71272. }
  71273. return angDiff;
  71274. };
  71275. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71276. ang1 %= (2 * Math.PI);
  71277. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71278. ang2 %= (2 * Math.PI);
  71279. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71280. var ab = 0;
  71281. if (ang1 < ang2) {
  71282. ab = ang2 - ang1;
  71283. }
  71284. else {
  71285. ab = ang1 - ang2;
  71286. }
  71287. if (ab > Math.PI) {
  71288. ab = Math.PI * 2 - ab;
  71289. }
  71290. return ab;
  71291. };
  71292. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71293. ang %= (2 * Math.PI);
  71294. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71295. ang1 %= (2 * Math.PI);
  71296. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71297. ang2 %= (2 * Math.PI);
  71298. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71299. if (ang1 < ang2) {
  71300. if (ang > ang1 && ang < ang2) {
  71301. return true;
  71302. }
  71303. }
  71304. else {
  71305. if (ang > ang2 && ang < ang1) {
  71306. return true;
  71307. }
  71308. }
  71309. return false;
  71310. };
  71311. 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()];
  71312. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71313. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71314. return BoneLookController;
  71315. }());
  71316. BABYLON.BoneLookController = BoneLookController;
  71317. })(BABYLON || (BABYLON = {}));
  71318. //# sourceMappingURL=babylon.boneLookController.js.map
  71319. var BABYLON;
  71320. (function (BABYLON) {
  71321. var Skeleton = /** @class */ (function () {
  71322. function Skeleton(name, id, scene) {
  71323. this.name = name;
  71324. this.id = id;
  71325. this.bones = new Array();
  71326. this.needInitialSkinMatrix = false;
  71327. this._isDirty = true;
  71328. this._meshesWithPoseMatrix = new Array();
  71329. this._identity = BABYLON.Matrix.Identity();
  71330. this._ranges = {};
  71331. this._lastAbsoluteTransformsUpdateId = -1;
  71332. /**
  71333. * Specifies if the skeleton should be serialized.
  71334. */
  71335. this.doNotSerialize = false;
  71336. // Events
  71337. /**
  71338. * An event triggered before computing the skeleton's matrices
  71339. * @type {BABYLON.Observable}
  71340. */
  71341. this.onBeforeComputeObservable = new BABYLON.Observable();
  71342. this.bones = [];
  71343. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71344. scene.skeletons.push(this);
  71345. //make sure it will recalculate the matrix next time prepare is called.
  71346. this._isDirty = true;
  71347. }
  71348. // Members
  71349. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71350. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71351. return mesh._bonesTransformMatrices;
  71352. }
  71353. if (!this._transformMatrices) {
  71354. this.prepare();
  71355. }
  71356. return this._transformMatrices;
  71357. };
  71358. Skeleton.prototype.getScene = function () {
  71359. return this._scene;
  71360. };
  71361. // Methods
  71362. /**
  71363. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71364. */
  71365. Skeleton.prototype.toString = function (fullDetails) {
  71366. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71367. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71368. if (fullDetails) {
  71369. ret += ", Ranges: {";
  71370. var first = true;
  71371. for (var name_1 in this._ranges) {
  71372. if (first) {
  71373. ret += ", ";
  71374. first = false;
  71375. }
  71376. ret += name_1;
  71377. }
  71378. ret += "}";
  71379. }
  71380. return ret;
  71381. };
  71382. /**
  71383. * Get bone's index searching by name
  71384. * @param {string} name is bone's name to search for
  71385. * @return {number} Indice of the bone. Returns -1 if not found
  71386. */
  71387. Skeleton.prototype.getBoneIndexByName = function (name) {
  71388. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71389. if (this.bones[boneIndex].name === name) {
  71390. return boneIndex;
  71391. }
  71392. }
  71393. return -1;
  71394. };
  71395. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71396. // check name not already in use
  71397. if (!this._ranges[name]) {
  71398. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71399. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71400. if (this.bones[i].animations[0]) {
  71401. this.bones[i].animations[0].createRange(name, from, to);
  71402. }
  71403. }
  71404. }
  71405. };
  71406. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71407. if (deleteFrames === void 0) { deleteFrames = true; }
  71408. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71409. if (this.bones[i].animations[0]) {
  71410. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71411. }
  71412. }
  71413. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71414. };
  71415. Skeleton.prototype.getAnimationRange = function (name) {
  71416. return this._ranges[name];
  71417. };
  71418. /**
  71419. * Returns as an Array, all AnimationRanges defined on this skeleton
  71420. */
  71421. Skeleton.prototype.getAnimationRanges = function () {
  71422. var animationRanges = [];
  71423. var name;
  71424. var i = 0;
  71425. for (name in this._ranges) {
  71426. animationRanges[i] = this._ranges[name];
  71427. i++;
  71428. }
  71429. return animationRanges;
  71430. };
  71431. /**
  71432. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71433. */
  71434. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71435. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71436. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71437. return false;
  71438. }
  71439. var ret = true;
  71440. var frameOffset = this._getHighestAnimationFrame() + 1;
  71441. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71442. var boneDict = {};
  71443. var sourceBones = source.bones;
  71444. var nBones;
  71445. var i;
  71446. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71447. boneDict[sourceBones[i].name] = sourceBones[i];
  71448. }
  71449. if (this.bones.length !== sourceBones.length) {
  71450. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71451. ret = false;
  71452. }
  71453. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71454. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71455. var boneName = this.bones[i].name;
  71456. var sourceBone = boneDict[boneName];
  71457. if (sourceBone) {
  71458. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71459. }
  71460. else {
  71461. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71462. ret = false;
  71463. }
  71464. }
  71465. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71466. var range = source.getAnimationRange(name);
  71467. if (range) {
  71468. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71469. }
  71470. return ret;
  71471. };
  71472. Skeleton.prototype.returnToRest = function () {
  71473. for (var index = 0; index < this.bones.length; index++) {
  71474. this.bones[index].returnToRest();
  71475. }
  71476. };
  71477. Skeleton.prototype._getHighestAnimationFrame = function () {
  71478. var ret = 0;
  71479. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71480. if (this.bones[i].animations[0]) {
  71481. var highest = this.bones[i].animations[0].getHighestFrame();
  71482. if (ret < highest) {
  71483. ret = highest;
  71484. }
  71485. }
  71486. }
  71487. return ret;
  71488. };
  71489. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71490. var range = this.getAnimationRange(name);
  71491. if (!range) {
  71492. return null;
  71493. }
  71494. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71495. };
  71496. Skeleton.prototype._markAsDirty = function () {
  71497. this._isDirty = true;
  71498. };
  71499. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71500. this._meshesWithPoseMatrix.push(mesh);
  71501. };
  71502. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71503. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71504. if (index > -1) {
  71505. this._meshesWithPoseMatrix.splice(index, 1);
  71506. }
  71507. };
  71508. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71509. this.onBeforeComputeObservable.notifyObservers(this);
  71510. for (var index = 0; index < this.bones.length; index++) {
  71511. var bone = this.bones[index];
  71512. var parentBone = bone.getParent();
  71513. if (parentBone) {
  71514. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71515. }
  71516. else {
  71517. if (initialSkinMatrix) {
  71518. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71519. }
  71520. else {
  71521. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71522. }
  71523. }
  71524. if (bone._index !== -1) {
  71525. var mappedIndex = bone._index === null ? index : bone._index;
  71526. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71527. }
  71528. }
  71529. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71530. };
  71531. Skeleton.prototype.prepare = function () {
  71532. if (!this._isDirty) {
  71533. return;
  71534. }
  71535. if (this.needInitialSkinMatrix) {
  71536. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71537. var mesh = this._meshesWithPoseMatrix[index];
  71538. var poseMatrix = mesh.getPoseMatrix();
  71539. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71540. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71541. }
  71542. if (this._synchronizedWithMesh !== mesh) {
  71543. this._synchronizedWithMesh = mesh;
  71544. // Prepare bones
  71545. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71546. var bone = this.bones[boneIndex];
  71547. if (!bone.getParent()) {
  71548. var matrix = bone.getBaseMatrix();
  71549. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71550. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71551. }
  71552. }
  71553. }
  71554. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71555. }
  71556. }
  71557. else {
  71558. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71559. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71560. }
  71561. this._computeTransformMatrices(this._transformMatrices, null);
  71562. }
  71563. this._isDirty = false;
  71564. this._scene._activeBones.addCount(this.bones.length, false);
  71565. };
  71566. Skeleton.prototype.getAnimatables = function () {
  71567. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71568. this._animatables = [];
  71569. for (var index = 0; index < this.bones.length; index++) {
  71570. this._animatables.push(this.bones[index]);
  71571. }
  71572. }
  71573. return this._animatables;
  71574. };
  71575. Skeleton.prototype.clone = function (name, id) {
  71576. var result = new Skeleton(name, id || name, this._scene);
  71577. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71578. for (var index = 0; index < this.bones.length; index++) {
  71579. var source = this.bones[index];
  71580. var parentBone = null;
  71581. var parent_1 = source.getParent();
  71582. if (parent_1) {
  71583. var parentIndex = this.bones.indexOf(parent_1);
  71584. parentBone = result.bones[parentIndex];
  71585. }
  71586. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71587. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71588. }
  71589. if (this._ranges) {
  71590. result._ranges = {};
  71591. for (var rangeName in this._ranges) {
  71592. var range = this._ranges[rangeName];
  71593. if (range) {
  71594. result._ranges[rangeName] = range.clone();
  71595. }
  71596. }
  71597. }
  71598. this._isDirty = true;
  71599. return result;
  71600. };
  71601. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71602. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71603. this.bones.forEach(function (bone) {
  71604. bone.animations.forEach(function (animation) {
  71605. animation.enableBlending = true;
  71606. animation.blendingSpeed = blendingSpeed;
  71607. });
  71608. });
  71609. };
  71610. Skeleton.prototype.dispose = function () {
  71611. this._meshesWithPoseMatrix = [];
  71612. // Animations
  71613. this.getScene().stopAnimation(this);
  71614. // Remove from scene
  71615. this.getScene().removeSkeleton(this);
  71616. };
  71617. Skeleton.prototype.serialize = function () {
  71618. var serializationObject = {};
  71619. serializationObject.name = this.name;
  71620. serializationObject.id = this.id;
  71621. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71622. serializationObject.bones = [];
  71623. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71624. for (var index = 0; index < this.bones.length; index++) {
  71625. var bone = this.bones[index];
  71626. var parent_2 = bone.getParent();
  71627. var serializedBone = {
  71628. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71629. name: bone.name,
  71630. matrix: bone.getBaseMatrix().toArray(),
  71631. rest: bone.getRestPose().toArray()
  71632. };
  71633. serializationObject.bones.push(serializedBone);
  71634. if (bone.length) {
  71635. serializedBone.length = bone.length;
  71636. }
  71637. if (bone.animations && bone.animations.length > 0) {
  71638. serializedBone.animation = bone.animations[0].serialize();
  71639. }
  71640. serializationObject.ranges = [];
  71641. for (var name in this._ranges) {
  71642. var source = this._ranges[name];
  71643. if (!source) {
  71644. continue;
  71645. }
  71646. var range = {};
  71647. range.name = name;
  71648. range.from = source.from;
  71649. range.to = source.to;
  71650. serializationObject.ranges.push(range);
  71651. }
  71652. }
  71653. return serializationObject;
  71654. };
  71655. Skeleton.Parse = function (parsedSkeleton, scene) {
  71656. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71657. if (parsedSkeleton.dimensionsAtRest) {
  71658. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71659. }
  71660. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71661. var index;
  71662. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71663. var parsedBone = parsedSkeleton.bones[index];
  71664. var parentBone = null;
  71665. if (parsedBone.parentBoneIndex > -1) {
  71666. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71667. }
  71668. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71669. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71670. if (parsedBone.length) {
  71671. bone.length = parsedBone.length;
  71672. }
  71673. if (parsedBone.animation) {
  71674. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71675. }
  71676. }
  71677. // placed after bones, so createAnimationRange can cascade down
  71678. if (parsedSkeleton.ranges) {
  71679. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71680. var data = parsedSkeleton.ranges[index];
  71681. skeleton.createAnimationRange(data.name, data.from, data.to);
  71682. }
  71683. }
  71684. return skeleton;
  71685. };
  71686. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71687. if (forceUpdate === void 0) { forceUpdate = false; }
  71688. var renderId = this._scene.getRenderId();
  71689. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71690. this.bones[0].computeAbsoluteTransforms();
  71691. this._lastAbsoluteTransformsUpdateId = renderId;
  71692. }
  71693. };
  71694. Skeleton.prototype.getPoseMatrix = function () {
  71695. var poseMatrix = null;
  71696. if (this._meshesWithPoseMatrix.length > 0) {
  71697. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71698. }
  71699. return poseMatrix;
  71700. };
  71701. Skeleton.prototype.sortBones = function () {
  71702. var bones = new Array();
  71703. var visited = new Array(this.bones.length);
  71704. for (var index = 0; index < this.bones.length; index++) {
  71705. this._sortBones(index, bones, visited);
  71706. }
  71707. this.bones = bones;
  71708. };
  71709. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71710. if (visited[index]) {
  71711. return;
  71712. }
  71713. visited[index] = true;
  71714. var bone = this.bones[index];
  71715. if (bone._index === undefined) {
  71716. bone._index = index;
  71717. }
  71718. var parentBone = bone.getParent();
  71719. if (parentBone) {
  71720. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71721. }
  71722. bones.push(bone);
  71723. };
  71724. return Skeleton;
  71725. }());
  71726. BABYLON.Skeleton = Skeleton;
  71727. })(BABYLON || (BABYLON = {}));
  71728. //# sourceMappingURL=babylon.skeleton.js.map
  71729. var BABYLON;
  71730. (function (BABYLON) {
  71731. var SphericalPolynomial = /** @class */ (function () {
  71732. function SphericalPolynomial() {
  71733. this.x = BABYLON.Vector3.Zero();
  71734. this.y = BABYLON.Vector3.Zero();
  71735. this.z = BABYLON.Vector3.Zero();
  71736. this.xx = BABYLON.Vector3.Zero();
  71737. this.yy = BABYLON.Vector3.Zero();
  71738. this.zz = BABYLON.Vector3.Zero();
  71739. this.xy = BABYLON.Vector3.Zero();
  71740. this.yz = BABYLON.Vector3.Zero();
  71741. this.zx = BABYLON.Vector3.Zero();
  71742. }
  71743. SphericalPolynomial.prototype.addAmbient = function (color) {
  71744. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71745. this.xx = this.xx.add(colorVector);
  71746. this.yy = this.yy.add(colorVector);
  71747. this.zz = this.zz.add(colorVector);
  71748. };
  71749. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71750. var result = new SphericalPolynomial();
  71751. result.x = harmonics.L11.scale(1.02333);
  71752. result.y = harmonics.L1_1.scale(1.02333);
  71753. result.z = harmonics.L10.scale(1.02333);
  71754. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71755. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71756. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71757. result.yz = harmonics.L2_1.scale(0.858086);
  71758. result.zx = harmonics.L21.scale(0.858086);
  71759. result.xy = harmonics.L2_2.scale(0.858086);
  71760. result.scale(1.0 / Math.PI);
  71761. return result;
  71762. };
  71763. SphericalPolynomial.prototype.scale = function (scale) {
  71764. this.x = this.x.scale(scale);
  71765. this.y = this.y.scale(scale);
  71766. this.z = this.z.scale(scale);
  71767. this.xx = this.xx.scale(scale);
  71768. this.yy = this.yy.scale(scale);
  71769. this.zz = this.zz.scale(scale);
  71770. this.yz = this.yz.scale(scale);
  71771. this.zx = this.zx.scale(scale);
  71772. this.xy = this.xy.scale(scale);
  71773. };
  71774. return SphericalPolynomial;
  71775. }());
  71776. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71777. var SphericalHarmonics = /** @class */ (function () {
  71778. function SphericalHarmonics() {
  71779. this.L00 = BABYLON.Vector3.Zero();
  71780. this.L1_1 = BABYLON.Vector3.Zero();
  71781. this.L10 = BABYLON.Vector3.Zero();
  71782. this.L11 = BABYLON.Vector3.Zero();
  71783. this.L2_2 = BABYLON.Vector3.Zero();
  71784. this.L2_1 = BABYLON.Vector3.Zero();
  71785. this.L20 = BABYLON.Vector3.Zero();
  71786. this.L21 = BABYLON.Vector3.Zero();
  71787. this.L22 = BABYLON.Vector3.Zero();
  71788. }
  71789. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71790. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71791. var c = colorVector.scale(deltaSolidAngle);
  71792. this.L00 = this.L00.add(c.scale(0.282095));
  71793. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71794. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71795. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71796. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71797. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71798. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71799. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71800. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71801. };
  71802. SphericalHarmonics.prototype.scale = function (scale) {
  71803. this.L00 = this.L00.scale(scale);
  71804. this.L1_1 = this.L1_1.scale(scale);
  71805. this.L10 = this.L10.scale(scale);
  71806. this.L11 = this.L11.scale(scale);
  71807. this.L2_2 = this.L2_2.scale(scale);
  71808. this.L2_1 = this.L2_1.scale(scale);
  71809. this.L20 = this.L20.scale(scale);
  71810. this.L21 = this.L21.scale(scale);
  71811. this.L22 = this.L22.scale(scale);
  71812. };
  71813. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71814. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71815. //
  71816. // E_lm = A_l * L_lm
  71817. //
  71818. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71819. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71820. // the scaling factors are given in equation 9.
  71821. // Constant (Band 0)
  71822. this.L00 = this.L00.scale(3.141593);
  71823. // Linear (Band 1)
  71824. this.L1_1 = this.L1_1.scale(2.094395);
  71825. this.L10 = this.L10.scale(2.094395);
  71826. this.L11 = this.L11.scale(2.094395);
  71827. // Quadratic (Band 2)
  71828. this.L2_2 = this.L2_2.scale(0.785398);
  71829. this.L2_1 = this.L2_1.scale(0.785398);
  71830. this.L20 = this.L20.scale(0.785398);
  71831. this.L21 = this.L21.scale(0.785398);
  71832. this.L22 = this.L22.scale(0.785398);
  71833. };
  71834. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71835. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71836. // L = (1/pi) * E * rho
  71837. //
  71838. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71839. this.scale(1.0 / Math.PI);
  71840. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71841. // (The pixel shader must apply albedo after texture fetches, etc).
  71842. };
  71843. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71844. var result = new SphericalHarmonics();
  71845. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71846. result.L1_1 = polynomial.y.scale(0.977204);
  71847. result.L10 = polynomial.z.scale(0.977204);
  71848. result.L11 = polynomial.x.scale(0.977204);
  71849. result.L2_2 = polynomial.xy.scale(1.16538);
  71850. result.L2_1 = polynomial.yz.scale(1.16538);
  71851. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71852. result.L21 = polynomial.zx.scale(1.16538);
  71853. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71854. result.scale(Math.PI);
  71855. return result;
  71856. };
  71857. return SphericalHarmonics;
  71858. }());
  71859. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71860. })(BABYLON || (BABYLON = {}));
  71861. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71862. var BABYLON;
  71863. (function (BABYLON) {
  71864. var FileFaceOrientation = /** @class */ (function () {
  71865. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71866. this.name = name;
  71867. this.worldAxisForNormal = worldAxisForNormal;
  71868. this.worldAxisForFileX = worldAxisForFileX;
  71869. this.worldAxisForFileY = worldAxisForFileY;
  71870. }
  71871. return FileFaceOrientation;
  71872. }());
  71873. ;
  71874. /**
  71875. * Helper class dealing with the extraction of spherical polynomial dataArray
  71876. * from a cube map.
  71877. */
  71878. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71879. function CubeMapToSphericalPolynomialTools() {
  71880. }
  71881. /**
  71882. * Converts a texture to the according Spherical Polynomial data.
  71883. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71884. *
  71885. * @param texture The texture to extract the information from.
  71886. * @return The Spherical Polynomial data.
  71887. */
  71888. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71889. if (!texture.isCube) {
  71890. // Only supports cube Textures currently.
  71891. return null;
  71892. }
  71893. var size = texture.getSize().width;
  71894. var right = texture.readPixels(0);
  71895. var left = texture.readPixels(1);
  71896. var up;
  71897. var down;
  71898. if (texture.isRenderTarget) {
  71899. up = texture.readPixels(3);
  71900. down = texture.readPixels(2);
  71901. }
  71902. else {
  71903. up = texture.readPixels(2);
  71904. down = texture.readPixels(3);
  71905. }
  71906. var front = texture.readPixels(4);
  71907. var back = texture.readPixels(5);
  71908. var gammaSpace = texture.gammaSpace;
  71909. // Always read as RGBA.
  71910. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71911. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71912. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71913. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71914. }
  71915. var cubeInfo = {
  71916. size: size,
  71917. right: right,
  71918. left: left,
  71919. up: up,
  71920. down: down,
  71921. front: front,
  71922. back: back,
  71923. format: format,
  71924. type: type,
  71925. gammaSpace: gammaSpace,
  71926. };
  71927. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71928. };
  71929. /**
  71930. * Converts a cubemap to the according Spherical Polynomial data.
  71931. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71932. *
  71933. * @param cubeInfo The Cube map to extract the information from.
  71934. * @return The Spherical Polynomial data.
  71935. */
  71936. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71937. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71938. var totalSolidAngle = 0.0;
  71939. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71940. var du = 2.0 / cubeInfo.size;
  71941. var dv = du;
  71942. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71943. var minUV = du * 0.5 - 1.0;
  71944. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71945. var fileFace = this.FileFaces[faceIndex];
  71946. var dataArray = cubeInfo[fileFace.name];
  71947. var v = minUV;
  71948. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71949. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71950. // Because SP is still linear, so summation is fine in that basis.
  71951. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71952. for (var y = 0; y < cubeInfo.size; y++) {
  71953. var u = minUV;
  71954. for (var x = 0; x < cubeInfo.size; x++) {
  71955. // World direction (not normalised)
  71956. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71957. worldDirection.normalize();
  71958. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71959. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71960. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71961. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71962. // Handle Integer types.
  71963. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71964. r /= 255;
  71965. g /= 255;
  71966. b /= 255;
  71967. }
  71968. // Handle Gamma space textures.
  71969. if (cubeInfo.gammaSpace) {
  71970. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71971. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71972. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71973. }
  71974. var color = new BABYLON.Color3(r, g, b);
  71975. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71976. totalSolidAngle += deltaSolidAngle;
  71977. u += du;
  71978. }
  71979. v += dv;
  71980. }
  71981. }
  71982. // Solid angle for entire sphere is 4*pi
  71983. var sphereSolidAngle = 4.0 * Math.PI;
  71984. // Adjust the solid angle to allow for how many faces we processed.
  71985. var facesProcessed = 6.0;
  71986. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71987. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71988. // This is needed because the numerical integration over the cube uses a
  71989. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71990. // and also to compensate for accumulative error due to float precision in the summation.
  71991. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71992. sphericalHarmonics.scale(correctionFactor);
  71993. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71994. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71995. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71996. };
  71997. CubeMapToSphericalPolynomialTools.FileFaces = [
  71998. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71999. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72000. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72001. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72002. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72003. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72004. ];
  72005. return CubeMapToSphericalPolynomialTools;
  72006. }());
  72007. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72008. })(BABYLON || (BABYLON = {}));
  72009. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72010. var BABYLON;
  72011. (function (BABYLON) {
  72012. /**
  72013. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72014. */
  72015. var PanoramaToCubeMapTools = /** @class */ (function () {
  72016. function PanoramaToCubeMapTools() {
  72017. }
  72018. /**
  72019. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72020. *
  72021. * @param float32Array The source data.
  72022. * @param inputWidth The width of the input panorama.
  72023. * @param inputhHeight The height of the input panorama.
  72024. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72025. * @return The cubemap data
  72026. */
  72027. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72028. if (!float32Array) {
  72029. throw "ConvertPanoramaToCubemap: input cannot be null";
  72030. }
  72031. if (float32Array.length != inputWidth * inputHeight * 3) {
  72032. throw "ConvertPanoramaToCubemap: input size is wrong";
  72033. }
  72034. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72035. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72036. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72037. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72038. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72039. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72040. return {
  72041. front: textureFront,
  72042. back: textureBack,
  72043. left: textureLeft,
  72044. right: textureRight,
  72045. up: textureUp,
  72046. down: textureDown,
  72047. size: size,
  72048. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72049. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72050. gammaSpace: false,
  72051. };
  72052. };
  72053. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72054. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72055. var textureArray = new Float32Array(buffer);
  72056. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72057. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72058. var dy = 1 / texSize;
  72059. var fy = 0;
  72060. for (var y = 0; y < texSize; y++) {
  72061. var xv1 = faceData[0];
  72062. var xv2 = faceData[2];
  72063. for (var x = 0; x < texSize; x++) {
  72064. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72065. v.normalize();
  72066. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72067. // 3 channels per pixels
  72068. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72069. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72070. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72071. xv1 = xv1.add(rotDX1);
  72072. xv2 = xv2.add(rotDX2);
  72073. }
  72074. fy += dy;
  72075. }
  72076. return textureArray;
  72077. };
  72078. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72079. var theta = Math.atan2(vDir.z, vDir.x);
  72080. var phi = Math.acos(vDir.y);
  72081. while (theta < -Math.PI)
  72082. theta += 2 * Math.PI;
  72083. while (theta > Math.PI)
  72084. theta -= 2 * Math.PI;
  72085. var dx = theta / Math.PI;
  72086. var dy = phi / Math.PI;
  72087. // recenter.
  72088. dx = dx * 0.5 + 0.5;
  72089. var px = Math.round(dx * inputWidth);
  72090. if (px < 0)
  72091. px = 0;
  72092. else if (px >= inputWidth)
  72093. px = inputWidth - 1;
  72094. var py = Math.round(dy * inputHeight);
  72095. if (py < 0)
  72096. py = 0;
  72097. else if (py >= inputHeight)
  72098. py = inputHeight - 1;
  72099. var inputY = (inputHeight - py - 1);
  72100. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72101. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72102. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72103. return {
  72104. r: r,
  72105. g: g,
  72106. b: b
  72107. };
  72108. };
  72109. PanoramaToCubeMapTools.FACE_FRONT = [
  72110. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72111. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72112. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72113. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72114. ];
  72115. PanoramaToCubeMapTools.FACE_BACK = [
  72116. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72117. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72118. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72119. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72120. ];
  72121. PanoramaToCubeMapTools.FACE_RIGHT = [
  72122. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72123. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72124. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72125. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72126. ];
  72127. PanoramaToCubeMapTools.FACE_LEFT = [
  72128. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72129. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72130. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72131. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72132. ];
  72133. PanoramaToCubeMapTools.FACE_DOWN = [
  72134. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72135. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72136. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72137. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72138. ];
  72139. PanoramaToCubeMapTools.FACE_UP = [
  72140. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72141. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72142. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72143. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72144. ];
  72145. return PanoramaToCubeMapTools;
  72146. }());
  72147. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72148. })(BABYLON || (BABYLON = {}));
  72149. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72150. var BABYLON;
  72151. (function (BABYLON) {
  72152. ;
  72153. /**
  72154. * This groups tools to convert HDR texture to native colors array.
  72155. */
  72156. var HDRTools = /** @class */ (function () {
  72157. function HDRTools() {
  72158. }
  72159. HDRTools.Ldexp = function (mantissa, exponent) {
  72160. if (exponent > 1023) {
  72161. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72162. }
  72163. if (exponent < -1074) {
  72164. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72165. }
  72166. return mantissa * Math.pow(2, exponent);
  72167. };
  72168. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72169. if (exponent > 0) {
  72170. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72171. float32array[index + 0] = red * exponent;
  72172. float32array[index + 1] = green * exponent;
  72173. float32array[index + 2] = blue * exponent;
  72174. }
  72175. else {
  72176. float32array[index + 0] = 0;
  72177. float32array[index + 1] = 0;
  72178. float32array[index + 2] = 0;
  72179. }
  72180. };
  72181. HDRTools.readStringLine = function (uint8array, startIndex) {
  72182. var line = "";
  72183. var character = "";
  72184. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72185. character = String.fromCharCode(uint8array[i]);
  72186. if (character == "\n") {
  72187. break;
  72188. }
  72189. line += character;
  72190. }
  72191. return line;
  72192. };
  72193. /**
  72194. * Reads header information from an RGBE texture stored in a native array.
  72195. * More information on this format are available here:
  72196. * https://en.wikipedia.org/wiki/RGBE_image_format
  72197. *
  72198. * @param uint8array The binary file stored in native array.
  72199. * @return The header information.
  72200. */
  72201. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72202. var height = 0;
  72203. var width = 0;
  72204. var line = this.readStringLine(uint8array, 0);
  72205. if (line[0] != '#' || line[1] != '?') {
  72206. throw "Bad HDR Format.";
  72207. }
  72208. var endOfHeader = false;
  72209. var findFormat = false;
  72210. var lineIndex = 0;
  72211. do {
  72212. lineIndex += (line.length + 1);
  72213. line = this.readStringLine(uint8array, lineIndex);
  72214. if (line == "FORMAT=32-bit_rle_rgbe") {
  72215. findFormat = true;
  72216. }
  72217. else if (line.length == 0) {
  72218. endOfHeader = true;
  72219. }
  72220. } while (!endOfHeader);
  72221. if (!findFormat) {
  72222. throw "HDR Bad header format, unsupported FORMAT";
  72223. }
  72224. lineIndex += (line.length + 1);
  72225. line = this.readStringLine(uint8array, lineIndex);
  72226. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72227. var match = sizeRegexp.exec(line);
  72228. // TODO. Support +Y and -X if needed.
  72229. if (!match || match.length < 3) {
  72230. throw "HDR Bad header format, no size";
  72231. }
  72232. width = parseInt(match[2]);
  72233. height = parseInt(match[1]);
  72234. if (width < 8 || width > 0x7fff) {
  72235. throw "HDR Bad header format, unsupported size";
  72236. }
  72237. lineIndex += (line.length + 1);
  72238. return {
  72239. height: height,
  72240. width: width,
  72241. dataPosition: lineIndex
  72242. };
  72243. };
  72244. /**
  72245. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72246. * This RGBE texture needs to store the information as a panorama.
  72247. *
  72248. * More information on this format are available here:
  72249. * https://en.wikipedia.org/wiki/RGBE_image_format
  72250. *
  72251. * @param buffer The binary file stored in an array buffer.
  72252. * @param size The expected size of the extracted cubemap.
  72253. * @return The Cube Map information.
  72254. */
  72255. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72256. var uint8array = new Uint8Array(buffer);
  72257. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72258. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72259. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72260. return cubeMapData;
  72261. };
  72262. /**
  72263. * Returns the pixels data extracted from an RGBE texture.
  72264. * This pixels will be stored left to right up to down in the R G B order in one array.
  72265. *
  72266. * More information on this format are available here:
  72267. * https://en.wikipedia.org/wiki/RGBE_image_format
  72268. *
  72269. * @param uint8array The binary file stored in an array buffer.
  72270. * @param hdrInfo The header information of the file.
  72271. * @return The pixels data in RGB right to left up to down order.
  72272. */
  72273. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72274. // Keep for multi format supports.
  72275. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72276. };
  72277. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72278. var num_scanlines = hdrInfo.height;
  72279. var scanline_width = hdrInfo.width;
  72280. var a, b, c, d, count;
  72281. var dataIndex = hdrInfo.dataPosition;
  72282. var index = 0, endIndex = 0, i = 0;
  72283. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72284. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72285. // 3 channels of 4 bytes per pixel in float.
  72286. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72287. var resultArray = new Float32Array(resultBuffer);
  72288. // read in each successive scanline
  72289. while (num_scanlines > 0) {
  72290. a = uint8array[dataIndex++];
  72291. b = uint8array[dataIndex++];
  72292. c = uint8array[dataIndex++];
  72293. d = uint8array[dataIndex++];
  72294. if (a != 2 || b != 2 || (c & 0x80)) {
  72295. // this file is not run length encoded
  72296. throw "HDR Bad header format, not RLE";
  72297. }
  72298. if (((c << 8) | d) != scanline_width) {
  72299. throw "HDR Bad header format, wrong scan line width";
  72300. }
  72301. index = 0;
  72302. // read each of the four channels for the scanline into the buffer
  72303. for (i = 0; i < 4; i++) {
  72304. endIndex = (i + 1) * scanline_width;
  72305. while (index < endIndex) {
  72306. a = uint8array[dataIndex++];
  72307. b = uint8array[dataIndex++];
  72308. if (a > 128) {
  72309. // a run of the same value
  72310. count = a - 128;
  72311. if ((count == 0) || (count > endIndex - index)) {
  72312. throw "HDR Bad Format, bad scanline data (run)";
  72313. }
  72314. while (count-- > 0) {
  72315. scanLineArray[index++] = b;
  72316. }
  72317. }
  72318. else {
  72319. // a non-run
  72320. count = a;
  72321. if ((count == 0) || (count > endIndex - index)) {
  72322. throw "HDR Bad Format, bad scanline data (non-run)";
  72323. }
  72324. scanLineArray[index++] = b;
  72325. if (--count > 0) {
  72326. for (var j = 0; j < count; j++) {
  72327. scanLineArray[index++] = uint8array[dataIndex++];
  72328. }
  72329. }
  72330. }
  72331. }
  72332. }
  72333. // now convert data from buffer into floats
  72334. for (i = 0; i < scanline_width; i++) {
  72335. a = scanLineArray[i];
  72336. b = scanLineArray[i + scanline_width];
  72337. c = scanLineArray[i + 2 * scanline_width];
  72338. d = scanLineArray[i + 3 * scanline_width];
  72339. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72340. }
  72341. num_scanlines--;
  72342. }
  72343. return resultArray;
  72344. };
  72345. return HDRTools;
  72346. }());
  72347. BABYLON.HDRTools = HDRTools;
  72348. })(BABYLON || (BABYLON = {}));
  72349. //# sourceMappingURL=babylon.hdr.js.map
  72350. var BABYLON;
  72351. (function (BABYLON) {
  72352. /**
  72353. * This represents a texture coming from an HDR input.
  72354. *
  72355. * The only supported format is currently panorama picture stored in RGBE format.
  72356. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72357. */
  72358. var HDRCubeTexture = /** @class */ (function (_super) {
  72359. __extends(HDRCubeTexture, _super);
  72360. /**
  72361. * Instantiates an HDRTexture from the following parameters.
  72362. *
  72363. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72364. * @param scene The scene the texture will be used in
  72365. * @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.
  72366. * @param noMipmap Forces to not generate the mipmap if true
  72367. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72368. * @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)
  72369. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72370. */
  72371. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72372. if (noMipmap === void 0) { noMipmap = false; }
  72373. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72374. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72375. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72376. if (onLoad === void 0) { onLoad = null; }
  72377. if (onError === void 0) { onError = null; }
  72378. var _this = _super.call(this, scene) || this;
  72379. _this._useInGammaSpace = false;
  72380. _this._generateHarmonics = true;
  72381. _this._isBABYLONPreprocessed = false;
  72382. _this._onLoad = null;
  72383. _this._onError = null;
  72384. /**
  72385. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72386. */
  72387. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72388. /**
  72389. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72390. * This is usefull at run time to apply the good shader.
  72391. */
  72392. _this.isPMREM = false;
  72393. _this._isBlocking = true;
  72394. /**
  72395. * Gets or sets the center of the bounding box associated with the cube texture
  72396. * It must define where the camera used to render the texture was set
  72397. */
  72398. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72399. if (!url) {
  72400. return _this;
  72401. }
  72402. _this.name = url;
  72403. _this.url = url;
  72404. _this.hasAlpha = false;
  72405. _this.isCube = true;
  72406. _this._textureMatrix = BABYLON.Matrix.Identity();
  72407. _this._onLoad = onLoad;
  72408. _this._onError = onError;
  72409. _this.gammaSpace = false;
  72410. var caps = scene.getEngine().getCaps();
  72411. if (size) {
  72412. _this._isBABYLONPreprocessed = false;
  72413. _this._noMipmap = noMipmap;
  72414. _this._size = size;
  72415. _this._useInGammaSpace = useInGammaSpace;
  72416. _this._usePMREMGenerator = usePMREMGenerator &&
  72417. caps.textureLOD &&
  72418. caps.textureFloat &&
  72419. !_this._useInGammaSpace;
  72420. }
  72421. else {
  72422. _this._isBABYLONPreprocessed = true;
  72423. _this._noMipmap = false;
  72424. _this._useInGammaSpace = false;
  72425. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72426. !_this._useInGammaSpace;
  72427. }
  72428. _this.isPMREM = _this._usePMREMGenerator;
  72429. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72430. if (!_this._texture) {
  72431. if (!scene.useDelayedTextureLoading) {
  72432. _this.loadTexture();
  72433. }
  72434. else {
  72435. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72436. }
  72437. }
  72438. return _this;
  72439. }
  72440. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72441. /**
  72442. * Gets wether or not the texture is blocking during loading.
  72443. */
  72444. get: function () {
  72445. return this._isBlocking;
  72446. },
  72447. /**
  72448. * Sets wether or not the texture is blocking during loading.
  72449. */
  72450. set: function (value) {
  72451. this._isBlocking = value;
  72452. },
  72453. enumerable: true,
  72454. configurable: true
  72455. });
  72456. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72457. get: function () {
  72458. return this._boundingBoxSize;
  72459. },
  72460. /**
  72461. * Gets or sets the size of the bounding box associated with the cube texture
  72462. * When defined, the cubemap will switch to local mode
  72463. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72464. * @example https://www.babylonjs-playground.com/#RNASML
  72465. */
  72466. set: function (value) {
  72467. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72468. return;
  72469. }
  72470. this._boundingBoxSize = value;
  72471. var scene = this.getScene();
  72472. if (scene) {
  72473. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72474. }
  72475. },
  72476. enumerable: true,
  72477. configurable: true
  72478. });
  72479. /**
  72480. * Occurs when the file is a preprocessed .babylon.hdr file.
  72481. */
  72482. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72483. var _this = this;
  72484. var mipLevels = 0;
  72485. var floatArrayView = null;
  72486. var scene = this.getScene();
  72487. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72488. var mips = new Array();
  72489. if (!floatArrayView) {
  72490. return mips;
  72491. }
  72492. var startIndex = 30;
  72493. for (var level = 0; level < mipLevels; level++) {
  72494. mips.push([]);
  72495. // Fill each pixel of the mip level.
  72496. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72497. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72498. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72499. mips[level].push(faceData);
  72500. startIndex += faceSize;
  72501. }
  72502. }
  72503. return mips;
  72504. } : null;
  72505. var callback = function (buffer) {
  72506. var scene = _this.getScene();
  72507. if (!scene) {
  72508. return null;
  72509. }
  72510. // Create Native Array Views
  72511. var intArrayView = new Int32Array(buffer);
  72512. floatArrayView = new Float32Array(buffer);
  72513. // Fill header.
  72514. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72515. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72516. // Update Texture Information.
  72517. if (!_this._texture) {
  72518. return null;
  72519. }
  72520. _this._texture.updateSize(_this._size, _this._size);
  72521. // Fill polynomial information.
  72522. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72523. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72524. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72525. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72526. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72527. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72528. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72529. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72530. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72531. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72532. _this.sphericalPolynomial = sphericalPolynomial;
  72533. // Fill pixel data.
  72534. mipLevels = intArrayView[29]; // Number of mip levels.
  72535. var startIndex = 30;
  72536. var data = [];
  72537. var faceSize = Math.pow(_this._size, 2) * 3;
  72538. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72539. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72540. startIndex += faceSize;
  72541. }
  72542. var results = [];
  72543. var byteArray = null;
  72544. // Push each faces.
  72545. for (var k = 0; k < 6; k++) {
  72546. var dataFace = null;
  72547. // To be deprecated.
  72548. if (version === 1) {
  72549. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72550. dataFace = data[j];
  72551. }
  72552. // If special cases.
  72553. if (!mipmapGenerator && dataFace) {
  72554. if (!scene.getEngine().getCaps().textureFloat) {
  72555. // 3 channels of 1 bytes per pixel in bytes.
  72556. var byteBuffer = new ArrayBuffer(faceSize);
  72557. byteArray = new Uint8Array(byteBuffer);
  72558. }
  72559. for (var i = 0; i < _this._size * _this._size; i++) {
  72560. // Put in gamma space if requested.
  72561. if (_this._useInGammaSpace) {
  72562. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72563. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72564. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72565. }
  72566. // Convert to int texture for fallback.
  72567. if (byteArray) {
  72568. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72569. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72570. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72571. // May use luminance instead if the result is not accurate.
  72572. var max = Math.max(Math.max(r, g), b);
  72573. if (max > 255) {
  72574. var scale = 255 / max;
  72575. r *= scale;
  72576. g *= scale;
  72577. b *= scale;
  72578. }
  72579. byteArray[(i * 3) + 0] = r;
  72580. byteArray[(i * 3) + 1] = g;
  72581. byteArray[(i * 3) + 2] = b;
  72582. }
  72583. }
  72584. }
  72585. // Fill the array accordingly.
  72586. if (byteArray) {
  72587. results.push(byteArray);
  72588. }
  72589. else {
  72590. results.push(dataFace);
  72591. }
  72592. }
  72593. return results;
  72594. };
  72595. if (scene) {
  72596. 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);
  72597. }
  72598. };
  72599. /**
  72600. * Occurs when the file is raw .hdr file.
  72601. */
  72602. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72603. var _this = this;
  72604. var callback = function (buffer) {
  72605. var scene = _this.getScene();
  72606. if (!scene) {
  72607. return null;
  72608. }
  72609. // Extract the raw linear data.
  72610. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72611. // Generate harmonics if needed.
  72612. if (_this._generateHarmonics) {
  72613. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72614. _this.sphericalPolynomial = sphericalPolynomial;
  72615. }
  72616. var results = [];
  72617. var byteArray = null;
  72618. // Push each faces.
  72619. for (var j = 0; j < 6; j++) {
  72620. // Create uintarray fallback.
  72621. if (!scene.getEngine().getCaps().textureFloat) {
  72622. // 3 channels of 1 bytes per pixel in bytes.
  72623. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72624. byteArray = new Uint8Array(byteBuffer);
  72625. }
  72626. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72627. // If special cases.
  72628. if (_this._useInGammaSpace || byteArray) {
  72629. for (var i = 0; i < _this._size * _this._size; i++) {
  72630. // Put in gamma space if requested.
  72631. if (_this._useInGammaSpace) {
  72632. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72633. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72634. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72635. }
  72636. // Convert to int texture for fallback.
  72637. if (byteArray) {
  72638. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72639. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72640. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72641. // May use luminance instead if the result is not accurate.
  72642. var max = Math.max(Math.max(r, g), b);
  72643. if (max > 255) {
  72644. var scale = 255 / max;
  72645. r *= scale;
  72646. g *= scale;
  72647. b *= scale;
  72648. }
  72649. byteArray[(i * 3) + 0] = r;
  72650. byteArray[(i * 3) + 1] = g;
  72651. byteArray[(i * 3) + 2] = b;
  72652. }
  72653. }
  72654. }
  72655. if (byteArray) {
  72656. results.push(byteArray);
  72657. }
  72658. else {
  72659. results.push(dataFace);
  72660. }
  72661. }
  72662. return results;
  72663. };
  72664. var mipmapGenerator = null;
  72665. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72666. // if (!this._noMipmap &&
  72667. // this._usePMREMGenerator) {
  72668. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72669. // // Custom setup of the generator matching with the PBR shader values.
  72670. // var generator = new BABYLON.PMREMGenerator(data,
  72671. // this._size,
  72672. // this._size,
  72673. // 0,
  72674. // 3,
  72675. // this.getScene().getEngine().getCaps().textureFloat,
  72676. // 2048,
  72677. // 0.25,
  72678. // false,
  72679. // true);
  72680. // return generator.filterCubeMap();
  72681. // };
  72682. // }
  72683. var scene = this.getScene();
  72684. if (scene) {
  72685. 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);
  72686. }
  72687. };
  72688. /**
  72689. * Starts the loading process of the texture.
  72690. */
  72691. HDRCubeTexture.prototype.loadTexture = function () {
  72692. if (this._isBABYLONPreprocessed) {
  72693. this.loadBabylonTexture();
  72694. }
  72695. else {
  72696. this.loadHDRTexture();
  72697. }
  72698. };
  72699. HDRCubeTexture.prototype.clone = function () {
  72700. var scene = this.getScene();
  72701. if (!scene) {
  72702. return this;
  72703. }
  72704. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72705. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72706. // Base texture
  72707. newTexture.level = this.level;
  72708. newTexture.wrapU = this.wrapU;
  72709. newTexture.wrapV = this.wrapV;
  72710. newTexture.coordinatesIndex = this.coordinatesIndex;
  72711. newTexture.coordinatesMode = this.coordinatesMode;
  72712. return newTexture;
  72713. };
  72714. // Methods
  72715. HDRCubeTexture.prototype.delayLoad = function () {
  72716. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72717. return;
  72718. }
  72719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72720. this._texture = this._getFromCache(this.url, this._noMipmap);
  72721. if (!this._texture) {
  72722. this.loadTexture();
  72723. }
  72724. };
  72725. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72726. return this._textureMatrix;
  72727. };
  72728. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72729. this._textureMatrix = value;
  72730. };
  72731. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72732. var texture = null;
  72733. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72734. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72735. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72736. texture.name = parsedTexture.name;
  72737. texture.hasAlpha = parsedTexture.hasAlpha;
  72738. texture.level = parsedTexture.level;
  72739. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72740. texture.isBlocking = parsedTexture.isBlocking;
  72741. }
  72742. if (texture) {
  72743. if (parsedTexture.boundingBoxPosition) {
  72744. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72745. }
  72746. if (parsedTexture.boundingBoxSize) {
  72747. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72748. }
  72749. }
  72750. return texture;
  72751. };
  72752. HDRCubeTexture.prototype.serialize = function () {
  72753. if (!this.name) {
  72754. return null;
  72755. }
  72756. var serializationObject = {};
  72757. serializationObject.name = this.name;
  72758. serializationObject.hasAlpha = this.hasAlpha;
  72759. serializationObject.isCube = true;
  72760. serializationObject.level = this.level;
  72761. serializationObject.size = this._size;
  72762. serializationObject.coordinatesMode = this.coordinatesMode;
  72763. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72764. serializationObject.generateHarmonics = this._generateHarmonics;
  72765. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72766. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72767. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72768. serializationObject.noMipmap = this._noMipmap;
  72769. serializationObject.isBlocking = this._isBlocking;
  72770. return serializationObject;
  72771. };
  72772. /**
  72773. * Saves as a file the data contained in the texture in a binary format.
  72774. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72775. * as the spherical used in the lighting.
  72776. * @param url The HDR file url.
  72777. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72778. * @param onError Method called if any error happens during download.
  72779. * @return The packed binary data.
  72780. */
  72781. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72782. if (onError === void 0) { onError = null; }
  72783. var callback = function (buffer) {
  72784. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72785. // Returns a URL you can use as a href.
  72786. var objUrl = window.URL.createObjectURL(data);
  72787. // Simulates a link to it and click to dowload.
  72788. var a = document.createElement("a");
  72789. document.body.appendChild(a);
  72790. a.style.display = "none";
  72791. a.href = objUrl;
  72792. a.download = "envmap.babylon.hdr";
  72793. a.click();
  72794. };
  72795. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72796. };
  72797. /**
  72798. * Serializes the data contained in the texture in a binary format.
  72799. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72800. * as the spherical used in the lighting.
  72801. * @param url The HDR file url.
  72802. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72803. * @param onError Method called if any error happens during download.
  72804. * @return The packed binary data.
  72805. */
  72806. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72807. if (onError === void 0) { onError = null; }
  72808. // Needs the url tho create the texture.
  72809. if (!url) {
  72810. return;
  72811. }
  72812. // Check Power of two size.
  72813. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72814. return;
  72815. }
  72816. // Coming Back in 3.x.
  72817. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72818. };
  72819. HDRCubeTexture._facesMapping = [
  72820. "right",
  72821. "left",
  72822. "up",
  72823. "down",
  72824. "front",
  72825. "back"
  72826. ];
  72827. return HDRCubeTexture;
  72828. }(BABYLON.BaseTexture));
  72829. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72830. })(BABYLON || (BABYLON = {}));
  72831. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72832. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72833. // Huge respect for a such great lib.
  72834. // Earcut license:
  72835. // Copyright (c) 2016, Mapbox
  72836. //
  72837. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72838. // with or without fee is hereby granted, provided that the above copyright notice
  72839. // and this permission notice appear in all copies.
  72840. //
  72841. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72842. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72843. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72844. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72845. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72846. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72847. // THIS SOFTWARE.
  72848. var Earcut;
  72849. (function (Earcut) {
  72850. /**
  72851. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72852. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72853. * @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).
  72854. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72855. */
  72856. function earcut(data, holeIndices, dim) {
  72857. dim = dim || 2;
  72858. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72859. if (!outerNode)
  72860. return triangles;
  72861. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72862. if (hasHoles)
  72863. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72864. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72865. if (data.length > 80 * dim) {
  72866. minX = maxX = data[0];
  72867. minY = maxY = data[1];
  72868. for (var i = dim; i < outerLen; i += dim) {
  72869. x = data[i];
  72870. y = data[i + 1];
  72871. if (x < minX)
  72872. minX = x;
  72873. if (y < minY)
  72874. minY = y;
  72875. if (x > maxX)
  72876. maxX = x;
  72877. if (y > maxY)
  72878. maxY = y;
  72879. }
  72880. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72881. size = Math.max(maxX - minX, maxY - minY);
  72882. }
  72883. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72884. return triangles;
  72885. }
  72886. Earcut.earcut = earcut;
  72887. var Node = /** @class */ (function () {
  72888. function Node(i, x, y) {
  72889. this.i = i;
  72890. this.x = x;
  72891. this.y = y;
  72892. this.prev = null;
  72893. this.next = null;
  72894. this.z = null;
  72895. this.prevZ = null;
  72896. this.nextZ = null;
  72897. this.steiner = false;
  72898. }
  72899. return Node;
  72900. }());
  72901. // create a circular doubly linked list from polygon points in the specified winding order
  72902. function linkedList(data, start, end, dim, clockwise) {
  72903. var i, last = null;
  72904. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72905. for (i = start; i < end; i += dim)
  72906. last = insertNode(i, data[i], data[i + 1], last);
  72907. }
  72908. else {
  72909. for (i = end - dim; i >= start; i -= dim)
  72910. last = insertNode(i, data[i], data[i + 1], last);
  72911. }
  72912. if (last && equals(last, last.next)) {
  72913. removeNode(last);
  72914. last = last.next;
  72915. }
  72916. return last;
  72917. }
  72918. // eliminate colinear or duplicate points
  72919. function filterPoints(start, end) {
  72920. if (!start)
  72921. return start;
  72922. if (!end)
  72923. end = start;
  72924. var p = start, again;
  72925. do {
  72926. again = false;
  72927. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72928. removeNode(p);
  72929. p = end = p.prev;
  72930. if (p === p.next)
  72931. return undefined;
  72932. again = true;
  72933. }
  72934. else {
  72935. p = p.next;
  72936. }
  72937. } while (again || p !== end);
  72938. return end;
  72939. }
  72940. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72941. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72942. if (!ear)
  72943. return;
  72944. // interlink polygon nodes in z-order
  72945. if (!pass && size)
  72946. indexCurve(ear, minX, minY, size);
  72947. var stop = ear, prev, next;
  72948. // iterate through ears, slicing them one by one
  72949. while (ear.prev !== ear.next) {
  72950. prev = ear.prev;
  72951. next = ear.next;
  72952. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72953. // cut off the triangle
  72954. triangles.push(prev.i / dim);
  72955. triangles.push(ear.i / dim);
  72956. triangles.push(next.i / dim);
  72957. removeNode(ear);
  72958. // skipping the next vertice leads to less sliver triangles
  72959. ear = next.next;
  72960. stop = next.next;
  72961. continue;
  72962. }
  72963. ear = next;
  72964. // if we looped through the whole remaining polygon and can't find any more ears
  72965. if (ear === stop) {
  72966. // try filtering points and slicing again
  72967. if (!pass) {
  72968. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72969. // if this didn't work, try curing all small self-intersections locally
  72970. }
  72971. else if (pass === 1) {
  72972. ear = cureLocalIntersections(ear, triangles, dim);
  72973. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72974. // as a last resort, try splitting the remaining polygon into two
  72975. }
  72976. else if (pass === 2) {
  72977. splitEarcut(ear, triangles, dim, minX, minY, size);
  72978. }
  72979. break;
  72980. }
  72981. }
  72982. }
  72983. // check whether a polygon node forms a valid ear with adjacent nodes
  72984. function isEar(ear) {
  72985. var a = ear.prev, b = ear, c = ear.next;
  72986. if (area(a, b, c) >= 0)
  72987. return false; // reflex, can't be an ear
  72988. // now make sure we don't have other points inside the potential ear
  72989. var p = ear.next.next;
  72990. while (p !== ear.prev) {
  72991. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72992. area(p.prev, p, p.next) >= 0)
  72993. return false;
  72994. p = p.next;
  72995. }
  72996. return true;
  72997. }
  72998. function isEarHashed(ear, minX, minY, size) {
  72999. var a = ear.prev, b = ear, c = ear.next;
  73000. if (area(a, b, c) >= 0)
  73001. return false; // reflex, can't be an ear
  73002. // triangle bbox; min & max are calculated like this for speed
  73003. 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);
  73004. // z-order range for the current triangle bbox;
  73005. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73006. // first look for points inside the triangle in increasing z-order
  73007. var p = ear.nextZ;
  73008. while (p && p.z <= maxZ) {
  73009. if (p !== ear.prev &&
  73010. p !== ear.next &&
  73011. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73012. area(p.prev, p, p.next) >= 0)
  73013. return false;
  73014. p = p.nextZ;
  73015. }
  73016. // then look for points in decreasing z-order
  73017. p = ear.prevZ;
  73018. while (p && p.z >= minZ) {
  73019. if (p !== ear.prev &&
  73020. p !== ear.next &&
  73021. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73022. area(p.prev, p, p.next) >= 0)
  73023. return false;
  73024. p = p.prevZ;
  73025. }
  73026. return true;
  73027. }
  73028. // go through all polygon nodes and cure small local self-intersections
  73029. function cureLocalIntersections(start, triangles, dim) {
  73030. var p = start;
  73031. do {
  73032. var a = p.prev, b = p.next.next;
  73033. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73034. triangles.push(a.i / dim);
  73035. triangles.push(p.i / dim);
  73036. triangles.push(b.i / dim);
  73037. // remove two nodes involved
  73038. removeNode(p);
  73039. removeNode(p.next);
  73040. p = start = b;
  73041. }
  73042. p = p.next;
  73043. } while (p !== start);
  73044. return p;
  73045. }
  73046. // try splitting polygon into two and triangulate them independently
  73047. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73048. // look for a valid diagonal that divides the polygon into two
  73049. var a = start;
  73050. do {
  73051. var b = a.next.next;
  73052. while (b !== a.prev) {
  73053. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73054. // split the polygon in two by the diagonal
  73055. var c = splitPolygon(a, b);
  73056. // filter colinear points around the cuts
  73057. a = filterPoints(a, a.next);
  73058. c = filterPoints(c, c.next);
  73059. // run earcut on each half
  73060. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73061. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73062. return;
  73063. }
  73064. b = b.next;
  73065. }
  73066. a = a.next;
  73067. } while (a !== start);
  73068. }
  73069. // link every hole into the outer loop, producing a single-ring polygon without holes
  73070. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73071. var queue = [], i, len, start, end, list;
  73072. for (i = 0, len = holeIndices.length; i < len; i++) {
  73073. start = holeIndices[i] * dim;
  73074. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73075. list = linkedList(data, start, end, dim, false);
  73076. if (list === list.next)
  73077. list.steiner = true;
  73078. queue.push(getLeftmost(list));
  73079. }
  73080. queue.sort(compareX);
  73081. // process holes from left to right
  73082. for (i = 0; i < queue.length; i++) {
  73083. eliminateHole(queue[i], outerNode);
  73084. outerNode = filterPoints(outerNode, outerNode.next);
  73085. }
  73086. return outerNode;
  73087. }
  73088. function compareX(a, b) {
  73089. return a.x - b.x;
  73090. }
  73091. // find a bridge between vertices that connects hole with an outer ring and and link it
  73092. function eliminateHole(hole, outerNode) {
  73093. outerNode = findHoleBridge(hole, outerNode);
  73094. if (outerNode) {
  73095. var b = splitPolygon(outerNode, hole);
  73096. filterPoints(b, b.next);
  73097. }
  73098. }
  73099. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73100. function findHoleBridge(hole, outerNode) {
  73101. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73102. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73103. // segment's endpoint with lesser x will be potential connection point
  73104. do {
  73105. if (hy <= p.y && hy >= p.next.y) {
  73106. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73107. if (x <= hx && x > qx) {
  73108. qx = x;
  73109. if (x === hx) {
  73110. if (hy === p.y)
  73111. return p;
  73112. if (hy === p.next.y)
  73113. return p.next;
  73114. }
  73115. m = p.x < p.next.x ? p : p.next;
  73116. }
  73117. }
  73118. p = p.next;
  73119. } while (p !== outerNode);
  73120. if (!m)
  73121. return null;
  73122. if (hx === qx)
  73123. return m.prev; // hole touches outer segment; pick lower endpoint
  73124. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73125. // if there are no points found, we have a valid connection;
  73126. // otherwise choose the point of the minimum angle with the ray as connection point
  73127. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73128. p = m.next;
  73129. while (p !== stop) {
  73130. if (hx >= p.x &&
  73131. p.x >= mx &&
  73132. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73133. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73134. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73135. m = p;
  73136. tanMin = tan;
  73137. }
  73138. }
  73139. p = p.next;
  73140. }
  73141. return m;
  73142. }
  73143. // interlink polygon nodes in z-order
  73144. function indexCurve(start, minX, minY, size) {
  73145. var p = start;
  73146. do {
  73147. if (p.z === null)
  73148. p.z = zOrder(p.x, p.y, minX, minY, size);
  73149. p.prevZ = p.prev;
  73150. p.nextZ = p.next;
  73151. p = p.next;
  73152. } while (p !== start);
  73153. p.prevZ.nextZ = null;
  73154. p.prevZ = null;
  73155. sortLinked(p);
  73156. }
  73157. // Simon Tatham's linked list merge sort algorithm
  73158. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73159. function sortLinked(list) {
  73160. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73161. do {
  73162. p = list;
  73163. list = null;
  73164. tail = null;
  73165. numMerges = 0;
  73166. while (p) {
  73167. numMerges++;
  73168. q = p;
  73169. pSize = 0;
  73170. for (i = 0; i < inSize; i++) {
  73171. pSize++;
  73172. q = q.nextZ;
  73173. if (!q)
  73174. break;
  73175. }
  73176. qSize = inSize;
  73177. while (pSize > 0 || (qSize > 0 && q)) {
  73178. if (pSize === 0) {
  73179. e = q;
  73180. q = q.nextZ;
  73181. qSize--;
  73182. }
  73183. else if (qSize === 0 || !q) {
  73184. e = p;
  73185. p = p.nextZ;
  73186. pSize--;
  73187. }
  73188. else if (p.z <= q.z) {
  73189. e = p;
  73190. p = p.nextZ;
  73191. pSize--;
  73192. }
  73193. else {
  73194. e = q;
  73195. q = q.nextZ;
  73196. qSize--;
  73197. }
  73198. if (tail)
  73199. tail.nextZ = e;
  73200. else
  73201. list = e;
  73202. e.prevZ = tail;
  73203. tail = e;
  73204. }
  73205. p = q;
  73206. }
  73207. tail.nextZ = null;
  73208. inSize *= 2;
  73209. } while (numMerges > 1);
  73210. return list;
  73211. }
  73212. // z-order of a point given coords and size of the data bounding box
  73213. function zOrder(x, y, minX, minY, size) {
  73214. // coords are transformed into non-negative 15-bit integer range
  73215. x = 32767 * (x - minX) / size;
  73216. y = 32767 * (y - minY) / size;
  73217. x = (x | (x << 8)) & 0x00FF00FF;
  73218. x = (x | (x << 4)) & 0x0F0F0F0F;
  73219. x = (x | (x << 2)) & 0x33333333;
  73220. x = (x | (x << 1)) & 0x55555555;
  73221. y = (y | (y << 8)) & 0x00FF00FF;
  73222. y = (y | (y << 4)) & 0x0F0F0F0F;
  73223. y = (y | (y << 2)) & 0x33333333;
  73224. y = (y | (y << 1)) & 0x55555555;
  73225. return x | (y << 1);
  73226. }
  73227. // find the leftmost node of a polygon ring
  73228. function getLeftmost(start) {
  73229. var p = start, leftmost = start;
  73230. do {
  73231. if (p.x < leftmost.x)
  73232. leftmost = p;
  73233. p = p.next;
  73234. } while (p !== start);
  73235. return leftmost;
  73236. }
  73237. // check if a point lies within a convex triangle
  73238. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73239. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73240. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73241. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73242. }
  73243. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73244. function isValidDiagonal(a, b) {
  73245. return a.next.i !== b.i &&
  73246. a.prev.i !== b.i &&
  73247. !intersectsPolygon(a, b) &&
  73248. locallyInside(a, b) &&
  73249. locallyInside(b, a) &&
  73250. middleInside(a, b);
  73251. }
  73252. // signed area of a triangle
  73253. function area(p, q, r) {
  73254. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73255. }
  73256. // check if two points are equal
  73257. function equals(p1, p2) {
  73258. return p1.x === p2.x && p1.y === p2.y;
  73259. }
  73260. // check if two segments intersect
  73261. function intersects(p1, q1, p2, q2) {
  73262. if ((equals(p1, q1) && equals(p2, q2)) ||
  73263. (equals(p1, q2) && equals(p2, q1)))
  73264. return true;
  73265. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73266. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73267. }
  73268. // check if a polygon diagonal intersects any polygon segments
  73269. function intersectsPolygon(a, b) {
  73270. var p = a;
  73271. do {
  73272. if (p.i !== a.i &&
  73273. p.next.i !== a.i &&
  73274. p.i !== b.i &&
  73275. p.next.i !== b.i &&
  73276. intersects(p, p.next, a, b))
  73277. return true;
  73278. p = p.next;
  73279. } while (p !== a);
  73280. return false;
  73281. }
  73282. // check if a polygon diagonal is locally inside the polygon
  73283. function locallyInside(a, b) {
  73284. return area(a.prev, a, a.next) < 0
  73285. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73286. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73287. }
  73288. // check if the middle point of a polygon diagonal is inside the polygon
  73289. function middleInside(a, b) {
  73290. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73291. do {
  73292. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73293. inside = !inside;
  73294. p = p.next;
  73295. } while (p !== a);
  73296. return inside;
  73297. }
  73298. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73299. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73300. function splitPolygon(a, b) {
  73301. 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;
  73302. a.next = b;
  73303. b.prev = a;
  73304. a2.next = an;
  73305. an.prev = a2;
  73306. b2.next = a2;
  73307. a2.prev = b2;
  73308. bp.next = b2;
  73309. b2.prev = bp;
  73310. return b2;
  73311. }
  73312. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73313. function insertNode(i, x, y, last) {
  73314. var p = new Node(i, x, y);
  73315. if (!last) {
  73316. p.prev = p;
  73317. p.next = p;
  73318. }
  73319. else {
  73320. p.next = last.next;
  73321. p.prev = last;
  73322. last.next.prev = p;
  73323. last.next = p;
  73324. }
  73325. return p;
  73326. }
  73327. function removeNode(p) {
  73328. p.next.prev = p.prev;
  73329. p.prev.next = p.next;
  73330. if (p.prevZ)
  73331. p.prevZ.nextZ = p.nextZ;
  73332. if (p.nextZ)
  73333. p.nextZ.prevZ = p.prevZ;
  73334. }
  73335. /**
  73336. * return a percentage difference between the polygon area and its triangulation area;
  73337. * used to verify correctness of triangulation
  73338. */
  73339. function deviation(data, holeIndices, dim, triangles) {
  73340. var hasHoles = holeIndices && holeIndices.length;
  73341. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73342. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73343. if (hasHoles) {
  73344. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73345. var start = holeIndices[i] * dim;
  73346. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73347. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73348. }
  73349. }
  73350. var trianglesArea = 0;
  73351. for (i = 0; i < triangles.length; i += 3) {
  73352. var a = triangles[i] * dim;
  73353. var b = triangles[i + 1] * dim;
  73354. var c = triangles[i + 2] * dim;
  73355. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73356. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73357. }
  73358. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73359. }
  73360. Earcut.deviation = deviation;
  73361. ;
  73362. function signedArea(data, start, end, dim) {
  73363. var sum = 0;
  73364. for (var i = start, j = end - dim; i < end; i += dim) {
  73365. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73366. j = i;
  73367. }
  73368. return sum;
  73369. }
  73370. /**
  73371. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73372. */
  73373. function flatten(data) {
  73374. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73375. for (var i = 0; i < data.length; i++) {
  73376. for (var j = 0; j < data[i].length; j++) {
  73377. for (var d = 0; d < dim; d++)
  73378. result.vertices.push(data[i][j][d]);
  73379. }
  73380. if (i > 0) {
  73381. holeIndex += data[i - 1].length;
  73382. result.holes.push(holeIndex);
  73383. }
  73384. }
  73385. return result;
  73386. }
  73387. Earcut.flatten = flatten;
  73388. ;
  73389. })(Earcut || (Earcut = {}));
  73390. //# sourceMappingURL=babylon.earcut.js.map
  73391. var BABYLON;
  73392. (function (BABYLON) {
  73393. var IndexedVector2 = /** @class */ (function (_super) {
  73394. __extends(IndexedVector2, _super);
  73395. function IndexedVector2(original, index) {
  73396. var _this = _super.call(this, original.x, original.y) || this;
  73397. _this.index = index;
  73398. return _this;
  73399. }
  73400. return IndexedVector2;
  73401. }(BABYLON.Vector2));
  73402. var PolygonPoints = /** @class */ (function () {
  73403. function PolygonPoints() {
  73404. this.elements = new Array();
  73405. }
  73406. PolygonPoints.prototype.add = function (originalPoints) {
  73407. var _this = this;
  73408. var result = new Array();
  73409. originalPoints.forEach(function (point) {
  73410. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73411. var newPoint = new IndexedVector2(point, _this.elements.length);
  73412. result.push(newPoint);
  73413. _this.elements.push(newPoint);
  73414. }
  73415. });
  73416. return result;
  73417. };
  73418. PolygonPoints.prototype.computeBounds = function () {
  73419. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73420. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73421. this.elements.forEach(function (point) {
  73422. // x
  73423. if (point.x < lmin.x) {
  73424. lmin.x = point.x;
  73425. }
  73426. else if (point.x > lmax.x) {
  73427. lmax.x = point.x;
  73428. }
  73429. // y
  73430. if (point.y < lmin.y) {
  73431. lmin.y = point.y;
  73432. }
  73433. else if (point.y > lmax.y) {
  73434. lmax.y = point.y;
  73435. }
  73436. });
  73437. return {
  73438. min: lmin,
  73439. max: lmax,
  73440. width: lmax.x - lmin.x,
  73441. height: lmax.y - lmin.y
  73442. };
  73443. };
  73444. return PolygonPoints;
  73445. }());
  73446. var Polygon = /** @class */ (function () {
  73447. function Polygon() {
  73448. }
  73449. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73450. return [
  73451. new BABYLON.Vector2(xmin, ymin),
  73452. new BABYLON.Vector2(xmax, ymin),
  73453. new BABYLON.Vector2(xmax, ymax),
  73454. new BABYLON.Vector2(xmin, ymax)
  73455. ];
  73456. };
  73457. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73458. if (cx === void 0) { cx = 0; }
  73459. if (cy === void 0) { cy = 0; }
  73460. if (numberOfSides === void 0) { numberOfSides = 32; }
  73461. var result = new Array();
  73462. var angle = 0;
  73463. var increment = (Math.PI * 2) / numberOfSides;
  73464. for (var i = 0; i < numberOfSides; i++) {
  73465. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73466. angle -= increment;
  73467. }
  73468. return result;
  73469. };
  73470. Polygon.Parse = function (input) {
  73471. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73472. var i, result = [];
  73473. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73474. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73475. }
  73476. return result;
  73477. };
  73478. Polygon.StartingAt = function (x, y) {
  73479. return BABYLON.Path2.StartingAt(x, y);
  73480. };
  73481. return Polygon;
  73482. }());
  73483. BABYLON.Polygon = Polygon;
  73484. var PolygonMeshBuilder = /** @class */ (function () {
  73485. function PolygonMeshBuilder(name, contours, scene) {
  73486. this._points = new PolygonPoints();
  73487. this._outlinepoints = new PolygonPoints();
  73488. this._holes = new Array();
  73489. this._epoints = new Array();
  73490. this._eholes = new Array();
  73491. this._name = name;
  73492. this._scene = scene;
  73493. var points;
  73494. if (contours instanceof BABYLON.Path2) {
  73495. points = contours.getPoints();
  73496. }
  73497. else {
  73498. points = contours;
  73499. }
  73500. this._addToepoint(points);
  73501. this._points.add(points);
  73502. this._outlinepoints.add(points);
  73503. }
  73504. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73505. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73506. var p = points_1[_i];
  73507. this._epoints.push(p.x, p.y);
  73508. }
  73509. };
  73510. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73511. this._points.add(hole);
  73512. var holepoints = new PolygonPoints();
  73513. holepoints.add(hole);
  73514. this._holes.push(holepoints);
  73515. this._eholes.push(this._epoints.length / 2);
  73516. this._addToepoint(hole);
  73517. return this;
  73518. };
  73519. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73520. var _this = this;
  73521. if (updatable === void 0) { updatable = false; }
  73522. if (depth === void 0) { depth = 0; }
  73523. var result = new BABYLON.Mesh(this._name, this._scene);
  73524. var normals = new Array();
  73525. var positions = new Array();
  73526. var uvs = new Array();
  73527. var bounds = this._points.computeBounds();
  73528. this._points.elements.forEach(function (p) {
  73529. normals.push(0, 1.0, 0);
  73530. positions.push(p.x, 0, p.y);
  73531. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73532. });
  73533. var indices = new Array();
  73534. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73535. for (var i = 0; i < res.length; i++) {
  73536. indices.push(res[i]);
  73537. }
  73538. if (depth > 0) {
  73539. var positionscount = (positions.length / 3); //get the current pointcount
  73540. this._points.elements.forEach(function (p) {
  73541. normals.push(0, -1.0, 0);
  73542. positions.push(p.x, -depth, p.y);
  73543. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73544. });
  73545. var totalCount = indices.length;
  73546. for (var i = 0; i < totalCount; i += 3) {
  73547. var i0 = indices[i + 0];
  73548. var i1 = indices[i + 1];
  73549. var i2 = indices[i + 2];
  73550. indices.push(i2 + positionscount);
  73551. indices.push(i1 + positionscount);
  73552. indices.push(i0 + positionscount);
  73553. }
  73554. //Add the sides
  73555. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73556. this._holes.forEach(function (hole) {
  73557. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73558. });
  73559. }
  73560. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73561. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73562. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73563. result.setIndices(indices);
  73564. return result;
  73565. };
  73566. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73567. var StartIndex = positions.length / 3;
  73568. var ulength = 0;
  73569. for (var i = 0; i < points.elements.length; i++) {
  73570. var p = points.elements[i];
  73571. var p1;
  73572. if ((i + 1) > points.elements.length - 1) {
  73573. p1 = points.elements[0];
  73574. }
  73575. else {
  73576. p1 = points.elements[i + 1];
  73577. }
  73578. positions.push(p.x, 0, p.y);
  73579. positions.push(p.x, -depth, p.y);
  73580. positions.push(p1.x, 0, p1.y);
  73581. positions.push(p1.x, -depth, p1.y);
  73582. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73583. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73584. var v3 = v2.subtract(v1);
  73585. var v4 = new BABYLON.Vector3(0, 1, 0);
  73586. var vn = BABYLON.Vector3.Cross(v3, v4);
  73587. vn = vn.normalize();
  73588. uvs.push(ulength / bounds.width, 0);
  73589. uvs.push(ulength / bounds.width, 1);
  73590. ulength += v3.length();
  73591. uvs.push((ulength / bounds.width), 0);
  73592. uvs.push((ulength / bounds.width), 1);
  73593. if (!flip) {
  73594. normals.push(-vn.x, -vn.y, -vn.z);
  73595. normals.push(-vn.x, -vn.y, -vn.z);
  73596. normals.push(-vn.x, -vn.y, -vn.z);
  73597. normals.push(-vn.x, -vn.y, -vn.z);
  73598. indices.push(StartIndex);
  73599. indices.push(StartIndex + 1);
  73600. indices.push(StartIndex + 2);
  73601. indices.push(StartIndex + 1);
  73602. indices.push(StartIndex + 3);
  73603. indices.push(StartIndex + 2);
  73604. }
  73605. else {
  73606. normals.push(vn.x, vn.y, vn.z);
  73607. normals.push(vn.x, vn.y, vn.z);
  73608. normals.push(vn.x, vn.y, vn.z);
  73609. normals.push(vn.x, vn.y, vn.z);
  73610. indices.push(StartIndex);
  73611. indices.push(StartIndex + 2);
  73612. indices.push(StartIndex + 1);
  73613. indices.push(StartIndex + 1);
  73614. indices.push(StartIndex + 2);
  73615. indices.push(StartIndex + 3);
  73616. }
  73617. StartIndex += 4;
  73618. }
  73619. ;
  73620. };
  73621. return PolygonMeshBuilder;
  73622. }());
  73623. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73624. })(BABYLON || (BABYLON = {}));
  73625. //# sourceMappingURL=babylon.polygonMesh.js.map
  73626. var BABYLON;
  73627. (function (BABYLON) {
  73628. // Unique ID when we import meshes from Babylon to CSG
  73629. var currentCSGMeshId = 0;
  73630. // # class Vertex
  73631. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73632. // one to provide additional features like texture coordinates and vertex
  73633. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73634. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73635. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73636. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73637. // is not used anywhere else.
  73638. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73639. var Vertex = /** @class */ (function () {
  73640. function Vertex(pos, normal, uv) {
  73641. this.pos = pos;
  73642. this.normal = normal;
  73643. this.uv = uv;
  73644. }
  73645. Vertex.prototype.clone = function () {
  73646. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73647. };
  73648. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73649. // orientation of a polygon is flipped.
  73650. Vertex.prototype.flip = function () {
  73651. this.normal = this.normal.scale(-1);
  73652. };
  73653. // Create a new vertex between this vertex and `other` by linearly
  73654. // interpolating all properties using a parameter of `t`. Subclasses should
  73655. // override this to interpolate additional properties.
  73656. Vertex.prototype.interpolate = function (other, t) {
  73657. 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));
  73658. };
  73659. return Vertex;
  73660. }());
  73661. // # class Plane
  73662. // Represents a plane in 3D space.
  73663. var Plane = /** @class */ (function () {
  73664. function Plane(normal, w) {
  73665. this.normal = normal;
  73666. this.w = w;
  73667. }
  73668. Plane.FromPoints = function (a, b, c) {
  73669. var v0 = c.subtract(a);
  73670. var v1 = b.subtract(a);
  73671. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73672. return null;
  73673. }
  73674. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73675. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73676. };
  73677. Plane.prototype.clone = function () {
  73678. return new Plane(this.normal.clone(), this.w);
  73679. };
  73680. Plane.prototype.flip = function () {
  73681. this.normal.scaleInPlace(-1);
  73682. this.w = -this.w;
  73683. };
  73684. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73685. // fragments in the appropriate lists. Coplanar polygons go into either
  73686. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73687. // respect to this plane. Polygons in front or in back of this plane go into
  73688. // either `front` or `back`.
  73689. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73690. var COPLANAR = 0;
  73691. var FRONT = 1;
  73692. var BACK = 2;
  73693. var SPANNING = 3;
  73694. // Classify each point as well as the entire polygon into one of the above
  73695. // four classes.
  73696. var polygonType = 0;
  73697. var types = [];
  73698. var i;
  73699. var t;
  73700. for (i = 0; i < polygon.vertices.length; i++) {
  73701. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73702. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73703. polygonType |= type;
  73704. types.push(type);
  73705. }
  73706. // Put the polygon in the correct list, splitting it when necessary.
  73707. switch (polygonType) {
  73708. case COPLANAR:
  73709. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73710. break;
  73711. case FRONT:
  73712. front.push(polygon);
  73713. break;
  73714. case BACK:
  73715. back.push(polygon);
  73716. break;
  73717. case SPANNING:
  73718. var f = [], b = [];
  73719. for (i = 0; i < polygon.vertices.length; i++) {
  73720. var j = (i + 1) % polygon.vertices.length;
  73721. var ti = types[i], tj = types[j];
  73722. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73723. if (ti !== BACK)
  73724. f.push(vi);
  73725. if (ti !== FRONT)
  73726. b.push(ti !== BACK ? vi.clone() : vi);
  73727. if ((ti | tj) === SPANNING) {
  73728. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73729. var v = vi.interpolate(vj, t);
  73730. f.push(v);
  73731. b.push(v.clone());
  73732. }
  73733. }
  73734. var poly;
  73735. if (f.length >= 3) {
  73736. poly = new Polygon(f, polygon.shared);
  73737. if (poly.plane)
  73738. front.push(poly);
  73739. }
  73740. if (b.length >= 3) {
  73741. poly = new Polygon(b, polygon.shared);
  73742. if (poly.plane)
  73743. back.push(poly);
  73744. }
  73745. break;
  73746. }
  73747. };
  73748. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73749. // point is on the plane.
  73750. Plane.EPSILON = 1e-5;
  73751. return Plane;
  73752. }());
  73753. // # class Polygon
  73754. // Represents a convex polygon. The vertices used to initialize a polygon must
  73755. // be coplanar and form a convex loop.
  73756. //
  73757. // Each convex polygon has a `shared` property, which is shared between all
  73758. // polygons that are clones of each other or were split from the same polygon.
  73759. // This can be used to define per-polygon properties (such as surface color).
  73760. var Polygon = /** @class */ (function () {
  73761. function Polygon(vertices, shared) {
  73762. this.vertices = vertices;
  73763. this.shared = shared;
  73764. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73765. }
  73766. Polygon.prototype.clone = function () {
  73767. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73768. return new Polygon(vertices, this.shared);
  73769. };
  73770. Polygon.prototype.flip = function () {
  73771. this.vertices.reverse().map(function (v) { v.flip(); });
  73772. this.plane.flip();
  73773. };
  73774. return Polygon;
  73775. }());
  73776. // # class Node
  73777. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73778. // by picking a polygon to split along. That polygon (and all other coplanar
  73779. // polygons) are added directly to that node and the other polygons are added to
  73780. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73781. // no distinction between internal and leaf nodes.
  73782. var Node = /** @class */ (function () {
  73783. function Node(polygons) {
  73784. this.plane = null;
  73785. this.front = null;
  73786. this.back = null;
  73787. this.polygons = new Array();
  73788. if (polygons) {
  73789. this.build(polygons);
  73790. }
  73791. }
  73792. Node.prototype.clone = function () {
  73793. var node = new Node();
  73794. node.plane = this.plane && this.plane.clone();
  73795. node.front = this.front && this.front.clone();
  73796. node.back = this.back && this.back.clone();
  73797. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73798. return node;
  73799. };
  73800. // Convert solid space to empty space and empty space to solid space.
  73801. Node.prototype.invert = function () {
  73802. for (var i = 0; i < this.polygons.length; i++) {
  73803. this.polygons[i].flip();
  73804. }
  73805. if (this.plane) {
  73806. this.plane.flip();
  73807. }
  73808. if (this.front) {
  73809. this.front.invert();
  73810. }
  73811. if (this.back) {
  73812. this.back.invert();
  73813. }
  73814. var temp = this.front;
  73815. this.front = this.back;
  73816. this.back = temp;
  73817. };
  73818. // Recursively remove all polygons in `polygons` that are inside this BSP
  73819. // tree.
  73820. Node.prototype.clipPolygons = function (polygons) {
  73821. if (!this.plane)
  73822. return polygons.slice();
  73823. var front = new Array(), back = new Array();
  73824. for (var i = 0; i < polygons.length; i++) {
  73825. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73826. }
  73827. if (this.front) {
  73828. front = this.front.clipPolygons(front);
  73829. }
  73830. if (this.back) {
  73831. back = this.back.clipPolygons(back);
  73832. }
  73833. else {
  73834. back = [];
  73835. }
  73836. return front.concat(back);
  73837. };
  73838. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73839. // `bsp`.
  73840. Node.prototype.clipTo = function (bsp) {
  73841. this.polygons = bsp.clipPolygons(this.polygons);
  73842. if (this.front)
  73843. this.front.clipTo(bsp);
  73844. if (this.back)
  73845. this.back.clipTo(bsp);
  73846. };
  73847. // Return a list of all polygons in this BSP tree.
  73848. Node.prototype.allPolygons = function () {
  73849. var polygons = this.polygons.slice();
  73850. if (this.front)
  73851. polygons = polygons.concat(this.front.allPolygons());
  73852. if (this.back)
  73853. polygons = polygons.concat(this.back.allPolygons());
  73854. return polygons;
  73855. };
  73856. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73857. // new polygons are filtered down to the bottom of the tree and become new
  73858. // nodes there. Each set of polygons is partitioned using the first polygon
  73859. // (no heuristic is used to pick a good split).
  73860. Node.prototype.build = function (polygons) {
  73861. if (!polygons.length)
  73862. return;
  73863. if (!this.plane)
  73864. this.plane = polygons[0].plane.clone();
  73865. var front = new Array(), back = new Array();
  73866. for (var i = 0; i < polygons.length; i++) {
  73867. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73868. }
  73869. if (front.length) {
  73870. if (!this.front)
  73871. this.front = new Node();
  73872. this.front.build(front);
  73873. }
  73874. if (back.length) {
  73875. if (!this.back)
  73876. this.back = new Node();
  73877. this.back.build(back);
  73878. }
  73879. };
  73880. return Node;
  73881. }());
  73882. var CSG = /** @class */ (function () {
  73883. function CSG() {
  73884. this.polygons = new Array();
  73885. }
  73886. // Convert BABYLON.Mesh to BABYLON.CSG
  73887. CSG.FromMesh = function (mesh) {
  73888. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73889. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73890. if (mesh instanceof BABYLON.Mesh) {
  73891. mesh.computeWorldMatrix(true);
  73892. matrix = mesh.getWorldMatrix();
  73893. meshPosition = mesh.position.clone();
  73894. meshRotation = mesh.rotation.clone();
  73895. if (mesh.rotationQuaternion) {
  73896. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73897. }
  73898. meshScaling = mesh.scaling.clone();
  73899. }
  73900. else {
  73901. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73902. }
  73903. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73904. var subMeshes = mesh.subMeshes;
  73905. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73906. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73907. vertices = [];
  73908. for (var j = 0; j < 3; j++) {
  73909. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73910. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73911. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73912. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73913. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73914. vertex = new Vertex(position, normal, uv);
  73915. vertices.push(vertex);
  73916. }
  73917. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73918. // To handle the case of degenerated triangle
  73919. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73920. if (polygon.plane)
  73921. polygons.push(polygon);
  73922. }
  73923. }
  73924. var csg = CSG.FromPolygons(polygons);
  73925. csg.matrix = matrix;
  73926. csg.position = meshPosition;
  73927. csg.rotation = meshRotation;
  73928. csg.scaling = meshScaling;
  73929. csg.rotationQuaternion = meshRotationQuaternion;
  73930. currentCSGMeshId++;
  73931. return csg;
  73932. };
  73933. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73934. CSG.FromPolygons = function (polygons) {
  73935. var csg = new CSG();
  73936. csg.polygons = polygons;
  73937. return csg;
  73938. };
  73939. CSG.prototype.clone = function () {
  73940. var csg = new CSG();
  73941. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73942. csg.copyTransformAttributes(this);
  73943. return csg;
  73944. };
  73945. CSG.prototype.union = function (csg) {
  73946. var a = new Node(this.clone().polygons);
  73947. var b = new Node(csg.clone().polygons);
  73948. a.clipTo(b);
  73949. b.clipTo(a);
  73950. b.invert();
  73951. b.clipTo(a);
  73952. b.invert();
  73953. a.build(b.allPolygons());
  73954. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73955. };
  73956. CSG.prototype.unionInPlace = function (csg) {
  73957. var a = new Node(this.polygons);
  73958. var b = new Node(csg.polygons);
  73959. a.clipTo(b);
  73960. b.clipTo(a);
  73961. b.invert();
  73962. b.clipTo(a);
  73963. b.invert();
  73964. a.build(b.allPolygons());
  73965. this.polygons = a.allPolygons();
  73966. };
  73967. CSG.prototype.subtract = function (csg) {
  73968. var a = new Node(this.clone().polygons);
  73969. var b = new Node(csg.clone().polygons);
  73970. a.invert();
  73971. a.clipTo(b);
  73972. b.clipTo(a);
  73973. b.invert();
  73974. b.clipTo(a);
  73975. b.invert();
  73976. a.build(b.allPolygons());
  73977. a.invert();
  73978. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73979. };
  73980. CSG.prototype.subtractInPlace = function (csg) {
  73981. var a = new Node(this.polygons);
  73982. var b = new Node(csg.polygons);
  73983. a.invert();
  73984. a.clipTo(b);
  73985. b.clipTo(a);
  73986. b.invert();
  73987. b.clipTo(a);
  73988. b.invert();
  73989. a.build(b.allPolygons());
  73990. a.invert();
  73991. this.polygons = a.allPolygons();
  73992. };
  73993. CSG.prototype.intersect = function (csg) {
  73994. var a = new Node(this.clone().polygons);
  73995. var b = new Node(csg.clone().polygons);
  73996. a.invert();
  73997. b.clipTo(a);
  73998. b.invert();
  73999. a.clipTo(b);
  74000. b.clipTo(a);
  74001. a.build(b.allPolygons());
  74002. a.invert();
  74003. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74004. };
  74005. CSG.prototype.intersectInPlace = function (csg) {
  74006. var a = new Node(this.polygons);
  74007. var b = new Node(csg.polygons);
  74008. a.invert();
  74009. b.clipTo(a);
  74010. b.invert();
  74011. a.clipTo(b);
  74012. b.clipTo(a);
  74013. a.build(b.allPolygons());
  74014. a.invert();
  74015. this.polygons = a.allPolygons();
  74016. };
  74017. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74018. // not modified.
  74019. CSG.prototype.inverse = function () {
  74020. var csg = this.clone();
  74021. csg.inverseInPlace();
  74022. return csg;
  74023. };
  74024. CSG.prototype.inverseInPlace = function () {
  74025. this.polygons.map(function (p) { p.flip(); });
  74026. };
  74027. // This is used to keep meshes transformations so they can be restored
  74028. // when we build back a Babylon Mesh
  74029. // NB : All CSG operations are performed in world coordinates
  74030. CSG.prototype.copyTransformAttributes = function (csg) {
  74031. this.matrix = csg.matrix;
  74032. this.position = csg.position;
  74033. this.rotation = csg.rotation;
  74034. this.scaling = csg.scaling;
  74035. this.rotationQuaternion = csg.rotationQuaternion;
  74036. return this;
  74037. };
  74038. // Build Raw mesh from CSG
  74039. // Coordinates here are in world space
  74040. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74041. var matrix = this.matrix.clone();
  74042. matrix.invert();
  74043. 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;
  74044. if (keepSubMeshes) {
  74045. // Sort Polygons, since subMeshes are indices range
  74046. polygons.sort(function (a, b) {
  74047. if (a.shared.meshId === b.shared.meshId) {
  74048. return a.shared.subMeshId - b.shared.subMeshId;
  74049. }
  74050. else {
  74051. return a.shared.meshId - b.shared.meshId;
  74052. }
  74053. });
  74054. }
  74055. for (var i = 0, il = polygons.length; i < il; i++) {
  74056. polygon = polygons[i];
  74057. // Building SubMeshes
  74058. if (!subMesh_dict[polygon.shared.meshId]) {
  74059. subMesh_dict[polygon.shared.meshId] = {};
  74060. }
  74061. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74062. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74063. indexStart: +Infinity,
  74064. indexEnd: -Infinity,
  74065. materialIndex: polygon.shared.materialIndex
  74066. };
  74067. }
  74068. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74069. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74070. polygonIndices[0] = 0;
  74071. polygonIndices[1] = j - 1;
  74072. polygonIndices[2] = j;
  74073. for (var k = 0; k < 3; k++) {
  74074. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74075. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74076. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74077. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74078. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74079. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74080. // Check if 2 points can be merged
  74081. if (!(typeof vertex_idx !== 'undefined' &&
  74082. normals[vertex_idx * 3] === localNormal.x &&
  74083. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74084. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74085. uvs[vertex_idx * 2] === uv.x &&
  74086. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74087. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74088. uvs.push(uv.x, uv.y);
  74089. normals.push(normal.x, normal.y, normal.z);
  74090. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74091. }
  74092. indices.push(vertex_idx);
  74093. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74094. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74095. currentIndex++;
  74096. }
  74097. }
  74098. }
  74099. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74100. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74101. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74102. mesh.setIndices(indices, null);
  74103. if (keepSubMeshes) {
  74104. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74105. var materialIndexOffset = 0, materialMaxIndex;
  74106. mesh.subMeshes = new Array();
  74107. for (var m in subMesh_dict) {
  74108. materialMaxIndex = -1;
  74109. for (var sm in subMesh_dict[m]) {
  74110. subMesh_obj = subMesh_dict[m][sm];
  74111. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74112. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74113. }
  74114. materialIndexOffset += ++materialMaxIndex;
  74115. }
  74116. }
  74117. return mesh;
  74118. };
  74119. // Build Mesh from CSG taking material and transforms into account
  74120. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74121. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74122. mesh.material = material;
  74123. mesh.position.copyFrom(this.position);
  74124. mesh.rotation.copyFrom(this.rotation);
  74125. if (this.rotationQuaternion) {
  74126. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74127. }
  74128. mesh.scaling.copyFrom(this.scaling);
  74129. mesh.computeWorldMatrix(true);
  74130. return mesh;
  74131. };
  74132. return CSG;
  74133. }());
  74134. BABYLON.CSG = CSG;
  74135. })(BABYLON || (BABYLON = {}));
  74136. //# sourceMappingURL=babylon.csg.js.map
  74137. var BABYLON;
  74138. (function (BABYLON) {
  74139. var LensFlare = /** @class */ (function () {
  74140. function LensFlare(size, position, color, imgUrl, system) {
  74141. this.size = size;
  74142. this.position = position;
  74143. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74144. this.color = color || new BABYLON.Color3(1, 1, 1);
  74145. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74146. this._system = system;
  74147. system.lensFlares.push(this);
  74148. }
  74149. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74150. return new LensFlare(size, position, color, imgUrl, system);
  74151. };
  74152. LensFlare.prototype.dispose = function () {
  74153. if (this.texture) {
  74154. this.texture.dispose();
  74155. }
  74156. // Remove from scene
  74157. var index = this._system.lensFlares.indexOf(this);
  74158. this._system.lensFlares.splice(index, 1);
  74159. };
  74160. ;
  74161. return LensFlare;
  74162. }());
  74163. BABYLON.LensFlare = LensFlare;
  74164. })(BABYLON || (BABYLON = {}));
  74165. //# sourceMappingURL=babylon.lensFlare.js.map
  74166. var BABYLON;
  74167. (function (BABYLON) {
  74168. var LensFlareSystem = /** @class */ (function () {
  74169. function LensFlareSystem(name, emitter, scene) {
  74170. this.name = name;
  74171. this.lensFlares = new Array();
  74172. this.borderLimit = 300;
  74173. this.viewportBorder = 0;
  74174. this.layerMask = 0x0FFFFFFF;
  74175. this._vertexBuffers = {};
  74176. this._isEnabled = true;
  74177. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74178. this._emitter = emitter;
  74179. this.id = name;
  74180. scene.lensFlareSystems.push(this);
  74181. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74182. var engine = scene.getEngine();
  74183. // VBO
  74184. var vertices = [];
  74185. vertices.push(1, 1);
  74186. vertices.push(-1, 1);
  74187. vertices.push(-1, -1);
  74188. vertices.push(1, -1);
  74189. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74190. // Indices
  74191. var indices = [];
  74192. indices.push(0);
  74193. indices.push(1);
  74194. indices.push(2);
  74195. indices.push(0);
  74196. indices.push(2);
  74197. indices.push(3);
  74198. this._indexBuffer = engine.createIndexBuffer(indices);
  74199. // Effects
  74200. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74201. }
  74202. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74203. get: function () {
  74204. return this._isEnabled;
  74205. },
  74206. set: function (value) {
  74207. this._isEnabled = value;
  74208. },
  74209. enumerable: true,
  74210. configurable: true
  74211. });
  74212. LensFlareSystem.prototype.getScene = function () {
  74213. return this._scene;
  74214. };
  74215. LensFlareSystem.prototype.getEmitter = function () {
  74216. return this._emitter;
  74217. };
  74218. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74219. this._emitter = newEmitter;
  74220. };
  74221. LensFlareSystem.prototype.getEmitterPosition = function () {
  74222. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74223. };
  74224. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74225. var position = this.getEmitterPosition();
  74226. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74227. this._positionX = position.x;
  74228. this._positionY = position.y;
  74229. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74230. if (this.viewportBorder > 0) {
  74231. globalViewport.x -= this.viewportBorder;
  74232. globalViewport.y -= this.viewportBorder;
  74233. globalViewport.width += this.viewportBorder * 2;
  74234. globalViewport.height += this.viewportBorder * 2;
  74235. position.x += this.viewportBorder;
  74236. position.y += this.viewportBorder;
  74237. this._positionX += this.viewportBorder;
  74238. this._positionY += this.viewportBorder;
  74239. }
  74240. if (position.z > 0) {
  74241. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74242. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74243. return true;
  74244. }
  74245. return true;
  74246. }
  74247. return false;
  74248. };
  74249. LensFlareSystem.prototype._isVisible = function () {
  74250. if (!this._isEnabled || !this._scene.activeCamera) {
  74251. return false;
  74252. }
  74253. var emitterPosition = this.getEmitterPosition();
  74254. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74255. var distance = direction.length();
  74256. direction.normalize();
  74257. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74258. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74259. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74260. };
  74261. LensFlareSystem.prototype.render = function () {
  74262. if (!this._effect.isReady() || !this._scene.activeCamera)
  74263. return false;
  74264. var engine = this._scene.getEngine();
  74265. var viewport = this._scene.activeCamera.viewport;
  74266. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74267. // Position
  74268. if (!this.computeEffectivePosition(globalViewport)) {
  74269. return false;
  74270. }
  74271. // Visibility
  74272. if (!this._isVisible()) {
  74273. return false;
  74274. }
  74275. // Intensity
  74276. var awayX;
  74277. var awayY;
  74278. if (this._positionX < this.borderLimit + globalViewport.x) {
  74279. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74280. }
  74281. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74282. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74283. }
  74284. else {
  74285. awayX = 0;
  74286. }
  74287. if (this._positionY < this.borderLimit + globalViewport.y) {
  74288. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74289. }
  74290. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74291. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74292. }
  74293. else {
  74294. awayY = 0;
  74295. }
  74296. var away = (awayX > awayY) ? awayX : awayY;
  74297. away -= this.viewportBorder;
  74298. if (away > this.borderLimit) {
  74299. away = this.borderLimit;
  74300. }
  74301. var intensity = 1.0 - (away / this.borderLimit);
  74302. if (intensity < 0) {
  74303. return false;
  74304. }
  74305. if (intensity > 1.0) {
  74306. intensity = 1.0;
  74307. }
  74308. if (this.viewportBorder > 0) {
  74309. globalViewport.x += this.viewportBorder;
  74310. globalViewport.y += this.viewportBorder;
  74311. globalViewport.width -= this.viewportBorder * 2;
  74312. globalViewport.height -= this.viewportBorder * 2;
  74313. this._positionX -= this.viewportBorder;
  74314. this._positionY -= this.viewportBorder;
  74315. }
  74316. // Position
  74317. var centerX = globalViewport.x + globalViewport.width / 2;
  74318. var centerY = globalViewport.y + globalViewport.height / 2;
  74319. var distX = centerX - this._positionX;
  74320. var distY = centerY - this._positionY;
  74321. // Effects
  74322. engine.enableEffect(this._effect);
  74323. engine.setState(false);
  74324. engine.setDepthBuffer(false);
  74325. // VBOs
  74326. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74327. // Flares
  74328. for (var index = 0; index < this.lensFlares.length; index++) {
  74329. var flare = this.lensFlares[index];
  74330. engine.setAlphaMode(flare.alphaMode);
  74331. var x = centerX - (distX * flare.position);
  74332. var y = centerY - (distY * flare.position);
  74333. var cw = flare.size;
  74334. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74335. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74336. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74337. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74338. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74339. // Texture
  74340. this._effect.setTexture("textureSampler", flare.texture);
  74341. // Color
  74342. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74343. // Draw order
  74344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74345. }
  74346. engine.setDepthBuffer(true);
  74347. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74348. return true;
  74349. };
  74350. LensFlareSystem.prototype.dispose = function () {
  74351. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74352. if (vertexBuffer) {
  74353. vertexBuffer.dispose();
  74354. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74355. }
  74356. if (this._indexBuffer) {
  74357. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74358. this._indexBuffer = null;
  74359. }
  74360. while (this.lensFlares.length) {
  74361. this.lensFlares[0].dispose();
  74362. }
  74363. // Remove from scene
  74364. var index = this._scene.lensFlareSystems.indexOf(this);
  74365. this._scene.lensFlareSystems.splice(index, 1);
  74366. };
  74367. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74368. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74369. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74370. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74371. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74372. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74373. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74374. var parsedFlare = parsedLensFlareSystem.flares[index];
  74375. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74376. }
  74377. return lensFlareSystem;
  74378. };
  74379. LensFlareSystem.prototype.serialize = function () {
  74380. var serializationObject = {};
  74381. serializationObject.id = this.id;
  74382. serializationObject.name = this.name;
  74383. serializationObject.emitterId = this.getEmitter().id;
  74384. serializationObject.borderLimit = this.borderLimit;
  74385. serializationObject.flares = [];
  74386. for (var index = 0; index < this.lensFlares.length; index++) {
  74387. var flare = this.lensFlares[index];
  74388. serializationObject.flares.push({
  74389. size: flare.size,
  74390. position: flare.position,
  74391. color: flare.color.asArray(),
  74392. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74393. });
  74394. }
  74395. return serializationObject;
  74396. };
  74397. return LensFlareSystem;
  74398. }());
  74399. BABYLON.LensFlareSystem = LensFlareSystem;
  74400. })(BABYLON || (BABYLON = {}));
  74401. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74402. var BABYLON;
  74403. (function (BABYLON) {
  74404. /**
  74405. * This is a holder class for the physics joint created by the physics plugin.
  74406. * It holds a set of functions to control the underlying joint.
  74407. */
  74408. var PhysicsJoint = /** @class */ (function () {
  74409. function PhysicsJoint(type, jointData) {
  74410. this.type = type;
  74411. this.jointData = jointData;
  74412. jointData.nativeParams = jointData.nativeParams || {};
  74413. }
  74414. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74415. get: function () {
  74416. return this._physicsJoint;
  74417. },
  74418. set: function (newJoint) {
  74419. if (this._physicsJoint) {
  74420. //remove from the wolrd
  74421. }
  74422. this._physicsJoint = newJoint;
  74423. },
  74424. enumerable: true,
  74425. configurable: true
  74426. });
  74427. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74428. set: function (physicsPlugin) {
  74429. this._physicsPlugin = physicsPlugin;
  74430. },
  74431. enumerable: true,
  74432. configurable: true
  74433. });
  74434. /**
  74435. * Execute a function that is physics-plugin specific.
  74436. * @param {Function} func the function that will be executed.
  74437. * It accepts two parameters: the physics world and the physics joint.
  74438. */
  74439. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74440. func(this._physicsPlugin.world, this._physicsJoint);
  74441. };
  74442. //TODO check if the native joints are the same
  74443. //Joint Types
  74444. PhysicsJoint.DistanceJoint = 0;
  74445. PhysicsJoint.HingeJoint = 1;
  74446. PhysicsJoint.BallAndSocketJoint = 2;
  74447. PhysicsJoint.WheelJoint = 3;
  74448. PhysicsJoint.SliderJoint = 4;
  74449. //OIMO
  74450. PhysicsJoint.PrismaticJoint = 5;
  74451. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74452. PhysicsJoint.UniversalJoint = 6;
  74453. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74454. //Cannon
  74455. //Similar to a Ball-Joint. Different in params
  74456. PhysicsJoint.PointToPointJoint = 8;
  74457. //Cannon only at the moment
  74458. PhysicsJoint.SpringJoint = 9;
  74459. PhysicsJoint.LockJoint = 10;
  74460. return PhysicsJoint;
  74461. }());
  74462. BABYLON.PhysicsJoint = PhysicsJoint;
  74463. /**
  74464. * A class representing a physics distance joint.
  74465. */
  74466. var DistanceJoint = /** @class */ (function (_super) {
  74467. __extends(DistanceJoint, _super);
  74468. function DistanceJoint(jointData) {
  74469. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74470. }
  74471. /**
  74472. * Update the predefined distance.
  74473. */
  74474. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74475. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74476. };
  74477. return DistanceJoint;
  74478. }(PhysicsJoint));
  74479. BABYLON.DistanceJoint = DistanceJoint;
  74480. var MotorEnabledJoint = /** @class */ (function (_super) {
  74481. __extends(MotorEnabledJoint, _super);
  74482. function MotorEnabledJoint(type, jointData) {
  74483. return _super.call(this, type, jointData) || this;
  74484. }
  74485. /**
  74486. * Set the motor values.
  74487. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74488. * @param {number} force the force to apply
  74489. * @param {number} maxForce max force for this motor.
  74490. */
  74491. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74492. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74493. };
  74494. /**
  74495. * Set the motor's limits.
  74496. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74497. */
  74498. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74499. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74500. };
  74501. return MotorEnabledJoint;
  74502. }(PhysicsJoint));
  74503. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74504. /**
  74505. * This class represents a single hinge physics joint
  74506. */
  74507. var HingeJoint = /** @class */ (function (_super) {
  74508. __extends(HingeJoint, _super);
  74509. function HingeJoint(jointData) {
  74510. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74511. }
  74512. /**
  74513. * Set the motor values.
  74514. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74515. * @param {number} force the force to apply
  74516. * @param {number} maxForce max force for this motor.
  74517. */
  74518. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74519. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74520. };
  74521. /**
  74522. * Set the motor's limits.
  74523. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74524. */
  74525. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74526. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74527. };
  74528. return HingeJoint;
  74529. }(MotorEnabledJoint));
  74530. BABYLON.HingeJoint = HingeJoint;
  74531. /**
  74532. * This class represents a dual hinge physics joint (same as wheel joint)
  74533. */
  74534. var Hinge2Joint = /** @class */ (function (_super) {
  74535. __extends(Hinge2Joint, _super);
  74536. function Hinge2Joint(jointData) {
  74537. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74538. }
  74539. /**
  74540. * Set the motor values.
  74541. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74542. * @param {number} force the force to apply
  74543. * @param {number} maxForce max force for this motor.
  74544. * @param {motorIndex} the motor's index, 0 or 1.
  74545. */
  74546. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74547. if (motorIndex === void 0) { motorIndex = 0; }
  74548. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74549. };
  74550. /**
  74551. * Set the motor limits.
  74552. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74553. * @param {number} upperLimit the upper limit
  74554. * @param {number} lowerLimit lower limit
  74555. * @param {motorIndex} the motor's index, 0 or 1.
  74556. */
  74557. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74558. if (motorIndex === void 0) { motorIndex = 0; }
  74559. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74560. };
  74561. return Hinge2Joint;
  74562. }(MotorEnabledJoint));
  74563. BABYLON.Hinge2Joint = Hinge2Joint;
  74564. })(BABYLON || (BABYLON = {}));
  74565. //# sourceMappingURL=babylon.physicsJoint.js.map
  74566. var BABYLON;
  74567. (function (BABYLON) {
  74568. var PhysicsImpostor = /** @class */ (function () {
  74569. function PhysicsImpostor(object, type, _options, _scene) {
  74570. if (_options === void 0) { _options = { mass: 0 }; }
  74571. var _this = this;
  74572. this.object = object;
  74573. this.type = type;
  74574. this._options = _options;
  74575. this._scene = _scene;
  74576. this._bodyUpdateRequired = false;
  74577. this._onBeforePhysicsStepCallbacks = new Array();
  74578. this._onAfterPhysicsStepCallbacks = new Array();
  74579. this._onPhysicsCollideCallbacks = [];
  74580. this._deltaPosition = BABYLON.Vector3.Zero();
  74581. this._isDisposed = false;
  74582. //temp variables for parent rotation calculations
  74583. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74584. this._tmpQuat = new BABYLON.Quaternion();
  74585. this._tmpQuat2 = new BABYLON.Quaternion();
  74586. /**
  74587. * this function is executed by the physics engine.
  74588. */
  74589. this.beforeStep = function () {
  74590. if (!_this._physicsEngine) {
  74591. return;
  74592. }
  74593. _this.object.translate(_this._deltaPosition, -1);
  74594. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74595. _this.object.computeWorldMatrix(false);
  74596. if (_this.object.parent && _this.object.rotationQuaternion) {
  74597. _this.getParentsRotation();
  74598. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74599. }
  74600. else {
  74601. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74602. }
  74603. if (!_this._options.disableBidirectionalTransformation) {
  74604. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74605. }
  74606. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74607. func(_this);
  74608. });
  74609. };
  74610. /**
  74611. * this function is executed by the physics engine.
  74612. */
  74613. this.afterStep = function () {
  74614. if (!_this._physicsEngine) {
  74615. return;
  74616. }
  74617. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74618. func(_this);
  74619. });
  74620. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74621. // object has now its world rotation. needs to be converted to local.
  74622. if (_this.object.parent && _this.object.rotationQuaternion) {
  74623. _this.getParentsRotation();
  74624. _this._tmpQuat.conjugateInPlace();
  74625. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74626. }
  74627. // take the position set and make it the absolute position of this object.
  74628. _this.object.setAbsolutePosition(_this.object.position);
  74629. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74630. _this.object.translate(_this._deltaPosition, 1);
  74631. };
  74632. /**
  74633. * Legacy collision detection event support
  74634. */
  74635. this.onCollideEvent = null;
  74636. //event and body object due to cannon's event-based architecture.
  74637. this.onCollide = function (e) {
  74638. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74639. return;
  74640. }
  74641. if (!_this._physicsEngine) {
  74642. return;
  74643. }
  74644. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74645. if (otherImpostor) {
  74646. // Legacy collision detection event support
  74647. if (_this.onCollideEvent) {
  74648. _this.onCollideEvent(_this, otherImpostor);
  74649. }
  74650. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74651. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74652. }).forEach(function (obj) {
  74653. obj.callback(_this, otherImpostor);
  74654. });
  74655. }
  74656. };
  74657. //sanity check!
  74658. if (!this.object) {
  74659. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74660. return;
  74661. }
  74662. //legacy support for old syntax.
  74663. if (!this._scene && object.getScene) {
  74664. this._scene = object.getScene();
  74665. }
  74666. if (!this._scene) {
  74667. return;
  74668. }
  74669. this._physicsEngine = this._scene.getPhysicsEngine();
  74670. if (!this._physicsEngine) {
  74671. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74672. }
  74673. else {
  74674. //set the object's quaternion, if not set
  74675. if (!this.object.rotationQuaternion) {
  74676. if (this.object.rotation) {
  74677. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74678. }
  74679. else {
  74680. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74681. }
  74682. }
  74683. //default options params
  74684. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74685. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74686. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74687. this._joints = [];
  74688. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74689. if (!this.object.parent || this._options.ignoreParent) {
  74690. this._init();
  74691. }
  74692. else if (this.object.parent.physicsImpostor) {
  74693. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74694. }
  74695. }
  74696. }
  74697. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74698. get: function () {
  74699. return this._isDisposed;
  74700. },
  74701. enumerable: true,
  74702. configurable: true
  74703. });
  74704. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74705. get: function () {
  74706. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74707. },
  74708. set: function (value) {
  74709. this.setMass(value);
  74710. },
  74711. enumerable: true,
  74712. configurable: true
  74713. });
  74714. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74715. get: function () {
  74716. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74717. },
  74718. set: function (value) {
  74719. if (!this._physicsEngine) {
  74720. return;
  74721. }
  74722. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74728. get: function () {
  74729. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74730. },
  74731. set: function (value) {
  74732. if (!this._physicsEngine) {
  74733. return;
  74734. }
  74735. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74736. },
  74737. enumerable: true,
  74738. configurable: true
  74739. });
  74740. /**
  74741. * This function will completly initialize this impostor.
  74742. * It will create a new body - but only if this mesh has no parent.
  74743. * If it has, this impostor will not be used other than to define the impostor
  74744. * of the child mesh.
  74745. */
  74746. PhysicsImpostor.prototype._init = function () {
  74747. if (!this._physicsEngine) {
  74748. return;
  74749. }
  74750. this._physicsEngine.removeImpostor(this);
  74751. this.physicsBody = null;
  74752. this._parent = this._parent || this._getPhysicsParent();
  74753. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74754. this._physicsEngine.addImpostor(this);
  74755. }
  74756. };
  74757. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74758. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74759. var parentMesh = this.object.parent;
  74760. return parentMesh.physicsImpostor;
  74761. }
  74762. return null;
  74763. };
  74764. /**
  74765. * Should a new body be generated.
  74766. */
  74767. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74768. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74769. };
  74770. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74771. this.forceUpdate();
  74772. };
  74773. /**
  74774. * Force a regeneration of this or the parent's impostor's body.
  74775. * Use under cautious - This will remove all joints already implemented.
  74776. */
  74777. PhysicsImpostor.prototype.forceUpdate = function () {
  74778. this._init();
  74779. if (this.parent && !this._options.ignoreParent) {
  74780. this.parent.forceUpdate();
  74781. }
  74782. };
  74783. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74784. /*public get mesh(): AbstractMesh {
  74785. return this._mesh;
  74786. }*/
  74787. /**
  74788. * Gets the body that holds this impostor. Either its own, or its parent.
  74789. */
  74790. get: function () {
  74791. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74792. },
  74793. /**
  74794. * Set the physics body. Used mainly by the physics engine/plugin
  74795. */
  74796. set: function (physicsBody) {
  74797. if (this._physicsBody && this._physicsEngine) {
  74798. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74799. }
  74800. this._physicsBody = physicsBody;
  74801. this.resetUpdateFlags();
  74802. },
  74803. enumerable: true,
  74804. configurable: true
  74805. });
  74806. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74807. get: function () {
  74808. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74809. },
  74810. set: function (value) {
  74811. this._parent = value;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74817. this._bodyUpdateRequired = false;
  74818. };
  74819. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74820. if (this.object.getBoundingInfo) {
  74821. var q = this.object.rotationQuaternion;
  74822. //reset rotation
  74823. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74824. //calculate the world matrix with no rotation
  74825. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74826. var boundingInfo = this.object.getBoundingInfo();
  74827. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74828. //bring back the rotation
  74829. this.object.rotationQuaternion = q;
  74830. //calculate the world matrix with the new rotation
  74831. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74832. return size;
  74833. }
  74834. else {
  74835. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74836. }
  74837. };
  74838. PhysicsImpostor.prototype.getObjectCenter = function () {
  74839. if (this.object.getBoundingInfo) {
  74840. var boundingInfo = this.object.getBoundingInfo();
  74841. return boundingInfo.boundingBox.centerWorld;
  74842. }
  74843. else {
  74844. return this.object.position;
  74845. }
  74846. };
  74847. /**
  74848. * Get a specific parametes from the options parameter.
  74849. */
  74850. PhysicsImpostor.prototype.getParam = function (paramName) {
  74851. return this._options[paramName];
  74852. };
  74853. /**
  74854. * Sets a specific parameter in the options given to the physics plugin
  74855. */
  74856. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74857. this._options[paramName] = value;
  74858. this._bodyUpdateRequired = true;
  74859. };
  74860. /**
  74861. * Specifically change the body's mass option. Won't recreate the physics body object
  74862. */
  74863. PhysicsImpostor.prototype.setMass = function (mass) {
  74864. if (this.getParam("mass") !== mass) {
  74865. this.setParam("mass", mass);
  74866. }
  74867. if (this._physicsEngine) {
  74868. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74869. }
  74870. };
  74871. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74872. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74873. };
  74874. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74875. if (this._physicsEngine) {
  74876. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74877. }
  74878. };
  74879. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74880. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74881. };
  74882. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74883. if (this._physicsEngine) {
  74884. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74885. }
  74886. };
  74887. /**
  74888. * Execute a function with the physics plugin native code.
  74889. * Provide a function the will have two variables - the world object and the physics body object.
  74890. */
  74891. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74892. if (this._physicsEngine) {
  74893. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74894. }
  74895. };
  74896. /**
  74897. * Register a function that will be executed before the physics world is stepping forward.
  74898. */
  74899. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74900. this._onBeforePhysicsStepCallbacks.push(func);
  74901. };
  74902. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74903. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74904. if (index > -1) {
  74905. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74906. }
  74907. else {
  74908. BABYLON.Tools.Warn("Function to remove was not found");
  74909. }
  74910. };
  74911. /**
  74912. * Register a function that will be executed after the physics step
  74913. */
  74914. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74915. this._onAfterPhysicsStepCallbacks.push(func);
  74916. };
  74917. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74918. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74919. if (index > -1) {
  74920. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74921. }
  74922. else {
  74923. BABYLON.Tools.Warn("Function to remove was not found");
  74924. }
  74925. };
  74926. /**
  74927. * register a function that will be executed when this impostor collides against a different body.
  74928. */
  74929. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74930. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74931. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74932. };
  74933. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74934. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74935. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74936. if (index > -1) {
  74937. this._onPhysicsCollideCallbacks.splice(index, 1);
  74938. }
  74939. else {
  74940. BABYLON.Tools.Warn("Function to remove was not found");
  74941. }
  74942. };
  74943. PhysicsImpostor.prototype.getParentsRotation = function () {
  74944. var parent = this.object.parent;
  74945. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74946. while (parent) {
  74947. if (parent.rotationQuaternion) {
  74948. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74949. }
  74950. else {
  74951. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74952. }
  74953. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74954. parent = parent.parent;
  74955. }
  74956. return this._tmpQuat;
  74957. };
  74958. /**
  74959. * Apply a force
  74960. */
  74961. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74962. if (this._physicsEngine) {
  74963. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74964. }
  74965. return this;
  74966. };
  74967. /**
  74968. * Apply an impulse
  74969. */
  74970. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74971. if (this._physicsEngine) {
  74972. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74973. }
  74974. return this;
  74975. };
  74976. /**
  74977. * A help function to create a joint.
  74978. */
  74979. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74980. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74981. this.addJoint(otherImpostor, joint);
  74982. return this;
  74983. };
  74984. /**
  74985. * Add a joint to this impostor with a different impostor.
  74986. */
  74987. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74988. this._joints.push({
  74989. otherImpostor: otherImpostor,
  74990. joint: joint
  74991. });
  74992. if (this._physicsEngine) {
  74993. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74994. }
  74995. return this;
  74996. };
  74997. /**
  74998. * Will keep this body still, in a sleep mode.
  74999. */
  75000. PhysicsImpostor.prototype.sleep = function () {
  75001. if (this._physicsEngine) {
  75002. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75003. }
  75004. return this;
  75005. };
  75006. /**
  75007. * Wake the body up.
  75008. */
  75009. PhysicsImpostor.prototype.wakeUp = function () {
  75010. if (this._physicsEngine) {
  75011. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75012. }
  75013. return this;
  75014. };
  75015. PhysicsImpostor.prototype.clone = function (newObject) {
  75016. if (!newObject)
  75017. return null;
  75018. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75019. };
  75020. PhysicsImpostor.prototype.dispose = function () {
  75021. var _this = this;
  75022. //no dispose if no physics engine is available.
  75023. if (!this._physicsEngine) {
  75024. return;
  75025. }
  75026. this._joints.forEach(function (j) {
  75027. if (_this._physicsEngine) {
  75028. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75029. }
  75030. });
  75031. //dispose the physics body
  75032. this._physicsEngine.removeImpostor(this);
  75033. if (this.parent) {
  75034. this.parent.forceUpdate();
  75035. }
  75036. else {
  75037. /*this._object.getChildMeshes().forEach(function(mesh) {
  75038. if (mesh.physicsImpostor) {
  75039. if (disposeChildren) {
  75040. mesh.physicsImpostor.dispose();
  75041. mesh.physicsImpostor = null;
  75042. }
  75043. }
  75044. })*/
  75045. }
  75046. this._isDisposed = true;
  75047. };
  75048. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75049. this._deltaPosition.copyFrom(position);
  75050. };
  75051. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75052. if (!this._deltaRotation) {
  75053. this._deltaRotation = new BABYLON.Quaternion();
  75054. }
  75055. this._deltaRotation.copyFrom(rotation);
  75056. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75057. };
  75058. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75059. if (this._physicsEngine) {
  75060. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75061. }
  75062. return this;
  75063. };
  75064. PhysicsImpostor.prototype.getRadius = function () {
  75065. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75066. };
  75067. /**
  75068. * Sync a bone with this impostor
  75069. * @param bone The bone to sync to the impostor.
  75070. * @param boneMesh The mesh that the bone is influencing.
  75071. * @param jointPivot The pivot of the joint / bone in local space.
  75072. * @param distToJoint Optional distance from the impostor to the joint.
  75073. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75074. */
  75075. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75076. var tempVec = PhysicsImpostor._tmpVecs[0];
  75077. var mesh = this.object;
  75078. if (mesh.rotationQuaternion) {
  75079. if (adjustRotation) {
  75080. var tempQuat = PhysicsImpostor._tmpQuat;
  75081. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75082. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75083. }
  75084. else {
  75085. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75086. }
  75087. }
  75088. tempVec.x = 0;
  75089. tempVec.y = 0;
  75090. tempVec.z = 0;
  75091. if (jointPivot) {
  75092. tempVec.x = jointPivot.x;
  75093. tempVec.y = jointPivot.y;
  75094. tempVec.z = jointPivot.z;
  75095. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75096. if (distToJoint === undefined || distToJoint === null) {
  75097. distToJoint = jointPivot.length();
  75098. }
  75099. tempVec.x *= distToJoint;
  75100. tempVec.y *= distToJoint;
  75101. tempVec.z *= distToJoint;
  75102. }
  75103. if (bone.getParent()) {
  75104. tempVec.addInPlace(mesh.getAbsolutePosition());
  75105. bone.setAbsolutePosition(tempVec, boneMesh);
  75106. }
  75107. else {
  75108. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75109. boneMesh.position.x -= tempVec.x;
  75110. boneMesh.position.y -= tempVec.y;
  75111. boneMesh.position.z -= tempVec.z;
  75112. }
  75113. };
  75114. /**
  75115. * Sync impostor to a bone
  75116. * @param bone The bone that the impostor will be synced to.
  75117. * @param boneMesh The mesh that the bone is influencing.
  75118. * @param jointPivot The pivot of the joint / bone in local space.
  75119. * @param distToJoint Optional distance from the impostor to the joint.
  75120. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75121. * @param boneAxis Optional vector3 axis the bone is aligned with
  75122. */
  75123. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75124. var mesh = this.object;
  75125. if (mesh.rotationQuaternion) {
  75126. if (adjustRotation) {
  75127. var tempQuat = PhysicsImpostor._tmpQuat;
  75128. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75129. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75130. }
  75131. else {
  75132. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75133. }
  75134. }
  75135. var pos = PhysicsImpostor._tmpVecs[0];
  75136. var boneDir = PhysicsImpostor._tmpVecs[1];
  75137. if (!boneAxis) {
  75138. boneAxis = PhysicsImpostor._tmpVecs[2];
  75139. boneAxis.x = 0;
  75140. boneAxis.y = 1;
  75141. boneAxis.z = 0;
  75142. }
  75143. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75144. bone.getAbsolutePositionToRef(boneMesh, pos);
  75145. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75146. distToJoint = jointPivot.length();
  75147. }
  75148. if (distToJoint !== undefined && distToJoint !== null) {
  75149. pos.x += boneDir.x * distToJoint;
  75150. pos.y += boneDir.y * distToJoint;
  75151. pos.z += boneDir.z * distToJoint;
  75152. }
  75153. mesh.setAbsolutePosition(pos);
  75154. };
  75155. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75156. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75157. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75158. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75159. //Impostor types
  75160. PhysicsImpostor.NoImpostor = 0;
  75161. PhysicsImpostor.SphereImpostor = 1;
  75162. PhysicsImpostor.BoxImpostor = 2;
  75163. PhysicsImpostor.PlaneImpostor = 3;
  75164. PhysicsImpostor.MeshImpostor = 4;
  75165. PhysicsImpostor.CylinderImpostor = 7;
  75166. PhysicsImpostor.ParticleImpostor = 8;
  75167. PhysicsImpostor.HeightmapImpostor = 9;
  75168. return PhysicsImpostor;
  75169. }());
  75170. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75171. })(BABYLON || (BABYLON = {}));
  75172. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75173. var BABYLON;
  75174. (function (BABYLON) {
  75175. var PhysicsEngine = /** @class */ (function () {
  75176. function PhysicsEngine(gravity, _physicsPlugin) {
  75177. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75178. this._physicsPlugin = _physicsPlugin;
  75179. //new methods and parameters
  75180. this._impostors = [];
  75181. this._joints = [];
  75182. if (!this._physicsPlugin.isSupported()) {
  75183. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75184. + "Please make sure it is included.");
  75185. }
  75186. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75187. this.setGravity(gravity);
  75188. this.setTimeStep();
  75189. }
  75190. PhysicsEngine.prototype.setGravity = function (gravity) {
  75191. this.gravity = gravity;
  75192. this._physicsPlugin.setGravity(this.gravity);
  75193. };
  75194. /**
  75195. * Set the time step of the physics engine.
  75196. * default is 1/60.
  75197. * To slow it down, enter 1/600 for example.
  75198. * To speed it up, 1/30
  75199. * @param {number} newTimeStep the new timestep to apply to this world.
  75200. */
  75201. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75202. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75203. this._physicsPlugin.setTimeStep(newTimeStep);
  75204. };
  75205. /**
  75206. * Get the time step of the physics engine.
  75207. */
  75208. PhysicsEngine.prototype.getTimeStep = function () {
  75209. return this._physicsPlugin.getTimeStep();
  75210. };
  75211. PhysicsEngine.prototype.dispose = function () {
  75212. this._impostors.forEach(function (impostor) {
  75213. impostor.dispose();
  75214. });
  75215. this._physicsPlugin.dispose();
  75216. };
  75217. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75218. return this._physicsPlugin.name;
  75219. };
  75220. /**
  75221. * Adding a new impostor for the impostor tracking.
  75222. * This will be done by the impostor itself.
  75223. * @param {PhysicsImpostor} impostor the impostor to add
  75224. */
  75225. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75226. impostor.uniqueId = this._impostors.push(impostor);
  75227. //if no parent, generate the body
  75228. if (!impostor.parent) {
  75229. this._physicsPlugin.generatePhysicsBody(impostor);
  75230. }
  75231. };
  75232. /**
  75233. * Remove an impostor from the engine.
  75234. * This impostor and its mesh will not longer be updated by the physics engine.
  75235. * @param {PhysicsImpostor} impostor the impostor to remove
  75236. */
  75237. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75238. var index = this._impostors.indexOf(impostor);
  75239. if (index > -1) {
  75240. var removed = this._impostors.splice(index, 1);
  75241. //Is it needed?
  75242. if (removed.length) {
  75243. //this will also remove it from the world.
  75244. removed[0].physicsBody = null;
  75245. }
  75246. }
  75247. };
  75248. /**
  75249. * Add a joint to the physics engine
  75250. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75251. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75252. * @param {PhysicsJoint} the joint that will connect both impostors.
  75253. */
  75254. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75255. var impostorJoint = {
  75256. mainImpostor: mainImpostor,
  75257. connectedImpostor: connectedImpostor,
  75258. joint: joint
  75259. };
  75260. joint.physicsPlugin = this._physicsPlugin;
  75261. this._joints.push(impostorJoint);
  75262. this._physicsPlugin.generateJoint(impostorJoint);
  75263. };
  75264. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75265. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75266. return (impostorJoint.connectedImpostor === connectedImpostor
  75267. && impostorJoint.joint === joint
  75268. && impostorJoint.mainImpostor === mainImpostor);
  75269. });
  75270. if (matchingJoints.length) {
  75271. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75272. //TODO remove it from the list as well
  75273. }
  75274. };
  75275. /**
  75276. * Called by the scene. no need to call it.
  75277. */
  75278. PhysicsEngine.prototype._step = function (delta) {
  75279. var _this = this;
  75280. //check if any mesh has no body / requires an update
  75281. this._impostors.forEach(function (impostor) {
  75282. if (impostor.isBodyInitRequired()) {
  75283. _this._physicsPlugin.generatePhysicsBody(impostor);
  75284. }
  75285. });
  75286. if (delta > 0.1) {
  75287. delta = 0.1;
  75288. }
  75289. else if (delta <= 0) {
  75290. delta = 1.0 / 60.0;
  75291. }
  75292. this._physicsPlugin.executeStep(delta, this._impostors);
  75293. };
  75294. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75295. return this._physicsPlugin;
  75296. };
  75297. PhysicsEngine.prototype.getImpostors = function () {
  75298. return this._impostors;
  75299. };
  75300. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75301. for (var i = 0; i < this._impostors.length; ++i) {
  75302. if (this._impostors[i].object === object) {
  75303. return this._impostors[i];
  75304. }
  75305. }
  75306. return null;
  75307. };
  75308. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75309. for (var i = 0; i < this._impostors.length; ++i) {
  75310. if (this._impostors[i].physicsBody === body) {
  75311. return this._impostors[i];
  75312. }
  75313. }
  75314. return null;
  75315. };
  75316. // Statics
  75317. PhysicsEngine.Epsilon = 0.001;
  75318. return PhysicsEngine;
  75319. }());
  75320. BABYLON.PhysicsEngine = PhysicsEngine;
  75321. })(BABYLON || (BABYLON = {}));
  75322. //# sourceMappingURL=babylon.physicsEngine.js.map
  75323. var BABYLON;
  75324. (function (BABYLON) {
  75325. var PhysicsHelper = /** @class */ (function () {
  75326. function PhysicsHelper(scene) {
  75327. this._scene = scene;
  75328. this._physicsEngine = this._scene.getPhysicsEngine();
  75329. if (!this._physicsEngine) {
  75330. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75331. }
  75332. }
  75333. /**
  75334. * @param {Vector3} origin the origin of the explosion
  75335. * @param {number} radius the explosion radius
  75336. * @param {number} strength the explosion strength
  75337. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75338. */
  75339. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75340. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75341. if (!this._physicsEngine) {
  75342. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75343. return null;
  75344. }
  75345. var impostors = this._physicsEngine.getImpostors();
  75346. if (impostors.length === 0) {
  75347. return null;
  75348. }
  75349. var event = new PhysicsRadialExplosionEvent(this._scene);
  75350. impostors.forEach(function (impostor) {
  75351. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75352. if (!impostorForceAndContactPoint) {
  75353. return;
  75354. }
  75355. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75356. });
  75357. event.dispose(false);
  75358. return event;
  75359. };
  75360. /**
  75361. * @param {Vector3} origin the origin of the explosion
  75362. * @param {number} radius the explosion radius
  75363. * @param {number} strength the explosion strength
  75364. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75365. */
  75366. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75367. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75368. if (!this._physicsEngine) {
  75369. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75370. return null;
  75371. }
  75372. var impostors = this._physicsEngine.getImpostors();
  75373. if (impostors.length === 0) {
  75374. return null;
  75375. }
  75376. var event = new PhysicsRadialExplosionEvent(this._scene);
  75377. impostors.forEach(function (impostor) {
  75378. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75379. if (!impostorForceAndContactPoint) {
  75380. return;
  75381. }
  75382. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75383. });
  75384. event.dispose(false);
  75385. return event;
  75386. };
  75387. /**
  75388. * @param {Vector3} origin the origin of the explosion
  75389. * @param {number} radius the explosion radius
  75390. * @param {number} strength the explosion strength
  75391. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75392. */
  75393. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75394. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75395. if (!this._physicsEngine) {
  75396. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75397. return null;
  75398. }
  75399. var impostors = this._physicsEngine.getImpostors();
  75400. if (impostors.length === 0) {
  75401. return null;
  75402. }
  75403. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75404. event.dispose(false);
  75405. return event;
  75406. };
  75407. /**
  75408. * @param {Vector3} origin the origin of the updraft
  75409. * @param {number} radius the radius of the updraft
  75410. * @param {number} strength the strength of the updraft
  75411. * @param {number} height the height of the updraft
  75412. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75413. */
  75414. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75415. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75416. if (!this._physicsEngine) {
  75417. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75418. return null;
  75419. }
  75420. if (this._physicsEngine.getImpostors().length === 0) {
  75421. return null;
  75422. }
  75423. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75424. event.dispose(false);
  75425. return event;
  75426. };
  75427. /**
  75428. * @param {Vector3} origin the of the vortex
  75429. * @param {number} radius the radius of the vortex
  75430. * @param {number} strength the strength of the vortex
  75431. * @param {number} height the height of the vortex
  75432. */
  75433. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75434. if (!this._physicsEngine) {
  75435. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75436. return null;
  75437. }
  75438. if (this._physicsEngine.getImpostors().length === 0) {
  75439. return null;
  75440. }
  75441. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75442. event.dispose(false);
  75443. return event;
  75444. };
  75445. return PhysicsHelper;
  75446. }());
  75447. BABYLON.PhysicsHelper = PhysicsHelper;
  75448. /***** Radial explosion *****/
  75449. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75450. function PhysicsRadialExplosionEvent(scene) {
  75451. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75452. this._rays = [];
  75453. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75454. this._scene = scene;
  75455. }
  75456. /**
  75457. * Returns the data related to the radial explosion event (sphere & rays).
  75458. * @returns {PhysicsRadialExplosionEventData}
  75459. */
  75460. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75461. this._dataFetched = true;
  75462. return {
  75463. sphere: this._sphere,
  75464. rays: this._rays,
  75465. };
  75466. };
  75467. /**
  75468. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75469. * @param impostor
  75470. * @param {Vector3} origin the origin of the explosion
  75471. * @param {number} radius the explosion radius
  75472. * @param {number} strength the explosion strength
  75473. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75474. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75475. */
  75476. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75477. if (impostor.mass === 0) {
  75478. return null;
  75479. }
  75480. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75481. return null;
  75482. }
  75483. if (impostor.object.getClassName() !== 'Mesh') {
  75484. return null;
  75485. }
  75486. var impostorObject = impostor.object;
  75487. var impostorObjectCenter = impostor.getObjectCenter();
  75488. var direction = impostorObjectCenter.subtract(origin);
  75489. var ray = new BABYLON.Ray(origin, direction, radius);
  75490. this._rays.push(ray);
  75491. var hit = ray.intersectsMesh(impostorObject);
  75492. var contactPoint = hit.pickedPoint;
  75493. if (!contactPoint) {
  75494. return null;
  75495. }
  75496. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75497. if (distanceFromOrigin > radius) {
  75498. return null;
  75499. }
  75500. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75501. ? strength
  75502. : strength * (1 - (distanceFromOrigin / radius));
  75503. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75504. return { force: force, contactPoint: contactPoint };
  75505. };
  75506. /**
  75507. * Disposes the sphere.
  75508. * @param {bolean} force
  75509. */
  75510. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75511. var _this = this;
  75512. if (force === void 0) { force = true; }
  75513. if (force) {
  75514. this._sphere.dispose();
  75515. }
  75516. else {
  75517. setTimeout(function () {
  75518. if (!_this._dataFetched) {
  75519. _this._sphere.dispose();
  75520. }
  75521. }, 0);
  75522. }
  75523. };
  75524. /*** Helpers ***/
  75525. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75526. if (!this._sphere) {
  75527. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75528. this._sphere.isVisible = false;
  75529. }
  75530. };
  75531. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75532. var impostorObject = impostor.object;
  75533. this._prepareSphere();
  75534. this._sphere.position = origin;
  75535. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75536. this._sphere._updateBoundingInfo();
  75537. this._sphere.computeWorldMatrix(true);
  75538. return this._sphere.intersectsMesh(impostorObject, true);
  75539. };
  75540. return PhysicsRadialExplosionEvent;
  75541. }());
  75542. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75543. /***** Gravitational Field *****/
  75544. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75545. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75546. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75547. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75548. this._physicsHelper = physicsHelper;
  75549. this._scene = scene;
  75550. this._origin = origin;
  75551. this._radius = radius;
  75552. this._strength = strength;
  75553. this._falloff = falloff;
  75554. this._tickCallback = this._tick.bind(this);
  75555. }
  75556. /**
  75557. * Returns the data related to the gravitational field event (sphere).
  75558. * @returns {PhysicsGravitationalFieldEventData}
  75559. */
  75560. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75561. this._dataFetched = true;
  75562. return {
  75563. sphere: this._sphere,
  75564. };
  75565. };
  75566. /**
  75567. * Enables the gravitational field.
  75568. */
  75569. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75570. this._tickCallback.call(this);
  75571. this._scene.registerBeforeRender(this._tickCallback);
  75572. };
  75573. /**
  75574. * Disables the gravitational field.
  75575. */
  75576. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75577. this._scene.unregisterBeforeRender(this._tickCallback);
  75578. };
  75579. /**
  75580. * Disposes the sphere.
  75581. * @param {bolean} force
  75582. */
  75583. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75584. var _this = this;
  75585. if (force === void 0) { force = true; }
  75586. if (force) {
  75587. this._sphere.dispose();
  75588. }
  75589. else {
  75590. setTimeout(function () {
  75591. if (!_this._dataFetched) {
  75592. _this._sphere.dispose();
  75593. }
  75594. }, 0);
  75595. }
  75596. };
  75597. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75598. // Since the params won't change, we fetch the event only once
  75599. if (this._sphere) {
  75600. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75601. }
  75602. else {
  75603. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75604. if (radialExplosionEvent) {
  75605. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75606. }
  75607. }
  75608. };
  75609. return PhysicsGravitationalFieldEvent;
  75610. }());
  75611. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75612. /***** Updraft *****/
  75613. var PhysicsUpdraftEvent = /** @class */ (function () {
  75614. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75615. this._scene = _scene;
  75616. this._origin = _origin;
  75617. this._radius = _radius;
  75618. this._strength = _strength;
  75619. this._height = _height;
  75620. this._updraftMode = _updraftMode;
  75621. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75622. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75623. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75624. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75625. this._physicsEngine = this._scene.getPhysicsEngine();
  75626. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75627. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75628. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75629. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75630. }
  75631. this._tickCallback = this._tick.bind(this);
  75632. }
  75633. /**
  75634. * Returns the data related to the updraft event (cylinder).
  75635. * @returns {PhysicsUpdraftEventData}
  75636. */
  75637. PhysicsUpdraftEvent.prototype.getData = function () {
  75638. this._dataFetched = true;
  75639. return {
  75640. cylinder: this._cylinder,
  75641. };
  75642. };
  75643. /**
  75644. * Enables the updraft.
  75645. */
  75646. PhysicsUpdraftEvent.prototype.enable = function () {
  75647. this._tickCallback.call(this);
  75648. this._scene.registerBeforeRender(this._tickCallback);
  75649. };
  75650. /**
  75651. * Disables the cortex.
  75652. */
  75653. PhysicsUpdraftEvent.prototype.disable = function () {
  75654. this._scene.unregisterBeforeRender(this._tickCallback);
  75655. };
  75656. /**
  75657. * Disposes the sphere.
  75658. * @param {bolean} force
  75659. */
  75660. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75661. var _this = this;
  75662. if (force === void 0) { force = true; }
  75663. if (force) {
  75664. this._cylinder.dispose();
  75665. }
  75666. else {
  75667. setTimeout(function () {
  75668. if (!_this._dataFetched) {
  75669. _this._cylinder.dispose();
  75670. }
  75671. }, 0);
  75672. }
  75673. };
  75674. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75675. if (impostor.mass === 0) {
  75676. return null;
  75677. }
  75678. if (!this._intersectsWithCylinder(impostor)) {
  75679. return null;
  75680. }
  75681. var impostorObjectCenter = impostor.getObjectCenter();
  75682. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75683. var direction = this._originDirection;
  75684. }
  75685. else {
  75686. var direction = impostorObjectCenter.subtract(this._originTop);
  75687. }
  75688. var multiplier = this._strength * -1;
  75689. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75690. return { force: force, contactPoint: impostorObjectCenter };
  75691. };
  75692. PhysicsUpdraftEvent.prototype._tick = function () {
  75693. var _this = this;
  75694. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75695. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75696. if (!impostorForceAndContactPoint) {
  75697. return;
  75698. }
  75699. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75700. });
  75701. };
  75702. /*** Helpers ***/
  75703. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75704. if (!this._cylinder) {
  75705. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75706. height: this._height,
  75707. diameter: this._radius * 2,
  75708. }, this._scene);
  75709. this._cylinder.isVisible = false;
  75710. }
  75711. };
  75712. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75713. var impostorObject = impostor.object;
  75714. this._prepareCylinder();
  75715. this._cylinder.position = this._cylinderPosition;
  75716. return this._cylinder.intersectsMesh(impostorObject, true);
  75717. };
  75718. return PhysicsUpdraftEvent;
  75719. }());
  75720. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75721. /***** Vortex *****/
  75722. var PhysicsVortexEvent = /** @class */ (function () {
  75723. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75724. this._scene = _scene;
  75725. this._origin = _origin;
  75726. this._radius = _radius;
  75727. this._strength = _strength;
  75728. this._height = _height;
  75729. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75730. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75731. this._updraftMultiplier = 0.02;
  75732. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75733. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75734. this._physicsEngine = this._scene.getPhysicsEngine();
  75735. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75736. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75737. this._tickCallback = this._tick.bind(this);
  75738. }
  75739. /**
  75740. * Returns the data related to the vortex event (cylinder).
  75741. * @returns {PhysicsVortexEventData}
  75742. */
  75743. PhysicsVortexEvent.prototype.getData = function () {
  75744. this._dataFetched = true;
  75745. return {
  75746. cylinder: this._cylinder,
  75747. };
  75748. };
  75749. /**
  75750. * Enables the vortex.
  75751. */
  75752. PhysicsVortexEvent.prototype.enable = function () {
  75753. this._tickCallback.call(this);
  75754. this._scene.registerBeforeRender(this._tickCallback);
  75755. };
  75756. /**
  75757. * Disables the cortex.
  75758. */
  75759. PhysicsVortexEvent.prototype.disable = function () {
  75760. this._scene.unregisterBeforeRender(this._tickCallback);
  75761. };
  75762. /**
  75763. * Disposes the sphere.
  75764. * @param {bolean} force
  75765. */
  75766. PhysicsVortexEvent.prototype.dispose = function (force) {
  75767. var _this = this;
  75768. if (force === void 0) { force = true; }
  75769. if (force) {
  75770. this._cylinder.dispose();
  75771. }
  75772. else {
  75773. setTimeout(function () {
  75774. if (!_this._dataFetched) {
  75775. _this._cylinder.dispose();
  75776. }
  75777. }, 0);
  75778. }
  75779. };
  75780. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75781. if (impostor.mass === 0) {
  75782. return null;
  75783. }
  75784. if (!this._intersectsWithCylinder(impostor)) {
  75785. return null;
  75786. }
  75787. if (impostor.object.getClassName() !== 'Mesh') {
  75788. return null;
  75789. }
  75790. var impostorObject = impostor.object;
  75791. var impostorObjectCenter = impostor.getObjectCenter();
  75792. 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)
  75793. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75794. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75795. var hit = ray.intersectsMesh(impostorObject);
  75796. var contactPoint = hit.pickedPoint;
  75797. if (!contactPoint) {
  75798. return null;
  75799. }
  75800. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75801. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75802. var directionToOrigin = contactPoint.normalize();
  75803. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75804. directionToOrigin = directionToOrigin.negate();
  75805. }
  75806. // TODO: find a more physically based solution
  75807. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75808. var forceX = directionToOrigin.x * this._strength / 8;
  75809. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75810. var forceZ = directionToOrigin.z * this._strength / 8;
  75811. }
  75812. else {
  75813. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75814. var forceY = this._originTop.y * this._updraftMultiplier;
  75815. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75816. }
  75817. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75818. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75819. return { force: force, contactPoint: impostorObjectCenter };
  75820. };
  75821. PhysicsVortexEvent.prototype._tick = function () {
  75822. var _this = this;
  75823. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75824. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75825. if (!impostorForceAndContactPoint) {
  75826. return;
  75827. }
  75828. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75829. });
  75830. };
  75831. /*** Helpers ***/
  75832. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75833. if (!this._cylinder) {
  75834. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75835. height: this._height,
  75836. diameter: this._radius * 2,
  75837. }, this._scene);
  75838. this._cylinder.isVisible = false;
  75839. }
  75840. };
  75841. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75842. var impostorObject = impostor.object;
  75843. this._prepareCylinder();
  75844. this._cylinder.position = this._cylinderPosition;
  75845. return this._cylinder.intersectsMesh(impostorObject, true);
  75846. };
  75847. return PhysicsVortexEvent;
  75848. }());
  75849. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75850. /***** Enums *****/
  75851. /**
  75852. * The strenght of the force in correspondence to the distance of the affected object
  75853. */
  75854. var PhysicsRadialImpulseFalloff;
  75855. (function (PhysicsRadialImpulseFalloff) {
  75856. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75857. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75858. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75859. /**
  75860. * The strenght of the force in correspondence to the distance of the affected object
  75861. */
  75862. var PhysicsUpdraftMode;
  75863. (function (PhysicsUpdraftMode) {
  75864. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75865. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75866. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75867. })(BABYLON || (BABYLON = {}));
  75868. //# sourceMappingURL=babylon.physicsHelper.js.map
  75869. var BABYLON;
  75870. (function (BABYLON) {
  75871. var CannonJSPlugin = /** @class */ (function () {
  75872. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75873. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75874. if (iterations === void 0) { iterations = 10; }
  75875. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75876. this.name = "CannonJSPlugin";
  75877. this._physicsMaterials = new Array();
  75878. this._fixedTimeStep = 1 / 60;
  75879. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75880. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75881. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75882. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75883. this._tmpPosition = BABYLON.Vector3.Zero();
  75884. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75885. this._tmpUnityRotation = new BABYLON.Quaternion();
  75886. if (!this.isSupported()) {
  75887. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75888. return;
  75889. }
  75890. this._extendNamespace();
  75891. this.world = new this.BJSCANNON.World();
  75892. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75893. this.world.solver.iterations = iterations;
  75894. }
  75895. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75896. this.world.gravity.copy(gravity);
  75897. };
  75898. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75899. this._fixedTimeStep = timeStep;
  75900. };
  75901. CannonJSPlugin.prototype.getTimeStep = function () {
  75902. return this._fixedTimeStep;
  75903. };
  75904. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75905. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75906. };
  75907. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75908. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75909. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75910. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75911. };
  75912. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75913. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75914. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75915. impostor.physicsBody.applyForce(impulse, worldPoint);
  75916. };
  75917. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75918. //parent-child relationship. Does this impostor has a parent impostor?
  75919. if (impostor.parent) {
  75920. if (impostor.physicsBody) {
  75921. this.removePhysicsBody(impostor);
  75922. //TODO is that needed?
  75923. impostor.forceUpdate();
  75924. }
  75925. return;
  75926. }
  75927. //should a new body be created for this impostor?
  75928. if (impostor.isBodyInitRequired()) {
  75929. var shape = this._createShape(impostor);
  75930. //unregister events, if body is being changed
  75931. var oldBody = impostor.physicsBody;
  75932. if (oldBody) {
  75933. this.removePhysicsBody(impostor);
  75934. }
  75935. //create the body and material
  75936. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75937. var bodyCreationObject = {
  75938. mass: impostor.getParam("mass"),
  75939. material: material
  75940. };
  75941. // A simple extend, in case native options were used.
  75942. var nativeOptions = impostor.getParam("nativeOptions");
  75943. for (var key in nativeOptions) {
  75944. if (nativeOptions.hasOwnProperty(key)) {
  75945. bodyCreationObject[key] = nativeOptions[key];
  75946. }
  75947. }
  75948. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75949. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75950. this.world.addEventListener("preStep", impostor.beforeStep);
  75951. this.world.addEventListener("postStep", impostor.afterStep);
  75952. impostor.physicsBody.addShape(shape);
  75953. this.world.add(impostor.physicsBody);
  75954. //try to keep the body moving in the right direction by taking old properties.
  75955. //Should be tested!
  75956. if (oldBody) {
  75957. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75958. impostor.physicsBody[param].copy(oldBody[param]);
  75959. });
  75960. }
  75961. this._processChildMeshes(impostor);
  75962. }
  75963. //now update the body's transformation
  75964. this._updatePhysicsBodyTransformation(impostor);
  75965. };
  75966. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75967. var _this = this;
  75968. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75969. var currentRotation = mainImpostor.object.rotationQuaternion;
  75970. if (meshChildren.length) {
  75971. var processMesh = function (localPosition, mesh) {
  75972. if (!currentRotation || !mesh.rotationQuaternion) {
  75973. return;
  75974. }
  75975. var childImpostor = mesh.getPhysicsImpostor();
  75976. if (childImpostor) {
  75977. var parent = childImpostor.parent;
  75978. if (parent !== mainImpostor) {
  75979. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75980. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75981. if (childImpostor.physicsBody) {
  75982. _this.removePhysicsBody(childImpostor);
  75983. childImpostor.physicsBody = null;
  75984. }
  75985. childImpostor.parent = mainImpostor;
  75986. childImpostor.resetUpdateFlags();
  75987. 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));
  75988. //Add the mass of the children.
  75989. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75990. }
  75991. }
  75992. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75993. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75994. };
  75995. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75996. }
  75997. };
  75998. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75999. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76000. this.world.removeEventListener("preStep", impostor.beforeStep);
  76001. this.world.removeEventListener("postStep", impostor.afterStep);
  76002. this.world.remove(impostor.physicsBody);
  76003. };
  76004. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76005. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76006. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76007. if (!mainBody || !connectedBody) {
  76008. return;
  76009. }
  76010. var constraint;
  76011. var jointData = impostorJoint.joint.jointData;
  76012. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76013. var constraintData = {
  76014. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76015. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76016. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76017. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76018. maxForce: jointData.nativeParams.maxForce,
  76019. collideConnected: !!jointData.collision
  76020. };
  76021. switch (impostorJoint.joint.type) {
  76022. case BABYLON.PhysicsJoint.HingeJoint:
  76023. case BABYLON.PhysicsJoint.Hinge2Joint:
  76024. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76025. break;
  76026. case BABYLON.PhysicsJoint.DistanceJoint:
  76027. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76028. break;
  76029. case BABYLON.PhysicsJoint.SpringJoint:
  76030. var springData = jointData;
  76031. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76032. restLength: springData.length,
  76033. stiffness: springData.stiffness,
  76034. damping: springData.damping,
  76035. localAnchorA: constraintData.pivotA,
  76036. localAnchorB: constraintData.pivotB
  76037. });
  76038. break;
  76039. case BABYLON.PhysicsJoint.LockJoint:
  76040. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76041. break;
  76042. case BABYLON.PhysicsJoint.PointToPointJoint:
  76043. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76044. default:
  76045. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76046. break;
  76047. }
  76048. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76049. constraint.collideConnected = !!jointData.collision;
  76050. impostorJoint.joint.physicsJoint = constraint;
  76051. //don't add spring as constraint, as it is not one.
  76052. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76053. this.world.addConstraint(constraint);
  76054. }
  76055. else {
  76056. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76057. constraint.applyForce();
  76058. });
  76059. }
  76060. };
  76061. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76062. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76063. };
  76064. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76065. var index;
  76066. var mat;
  76067. for (index = 0; index < this._physicsMaterials.length; index++) {
  76068. mat = this._physicsMaterials[index];
  76069. if (mat.friction === friction && mat.restitution === restitution) {
  76070. return mat;
  76071. }
  76072. }
  76073. var currentMat = new this.BJSCANNON.Material(name);
  76074. currentMat.friction = friction;
  76075. currentMat.restitution = restitution;
  76076. this._physicsMaterials.push(currentMat);
  76077. return currentMat;
  76078. };
  76079. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76080. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76081. };
  76082. CannonJSPlugin.prototype._createShape = function (impostor) {
  76083. var object = impostor.object;
  76084. var returnValue;
  76085. var extendSize = impostor.getObjectExtendSize();
  76086. switch (impostor.type) {
  76087. case BABYLON.PhysicsImpostor.SphereImpostor:
  76088. var radiusX = extendSize.x;
  76089. var radiusY = extendSize.y;
  76090. var radiusZ = extendSize.z;
  76091. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76092. break;
  76093. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76094. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76095. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76096. break;
  76097. case BABYLON.PhysicsImpostor.BoxImpostor:
  76098. var box = extendSize.scale(0.5);
  76099. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76100. break;
  76101. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76102. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76103. returnValue = new this.BJSCANNON.Plane();
  76104. break;
  76105. case BABYLON.PhysicsImpostor.MeshImpostor:
  76106. // should transform the vertex data to world coordinates!!
  76107. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76108. var rawFaces = object.getIndices ? object.getIndices() : [];
  76109. if (!rawVerts)
  76110. return;
  76111. // get only scale! so the object could transform correctly.
  76112. var oldPosition = object.position.clone();
  76113. var oldRotation = object.rotation && object.rotation.clone();
  76114. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76115. object.position.copyFromFloats(0, 0, 0);
  76116. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76117. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76118. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76119. var transform = object.computeWorldMatrix(true);
  76120. // convert rawVerts to object space
  76121. var temp = new Array();
  76122. var index;
  76123. for (index = 0; index < rawVerts.length; index += 3) {
  76124. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76125. }
  76126. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76127. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76128. //now set back the transformation!
  76129. object.position.copyFrom(oldPosition);
  76130. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76131. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76132. break;
  76133. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76134. var oldPosition2 = object.position.clone();
  76135. var oldRotation2 = object.rotation && object.rotation.clone();
  76136. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76137. object.position.copyFromFloats(0, 0, 0);
  76138. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76139. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76140. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76141. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76142. returnValue = this._createHeightmap(object);
  76143. object.position.copyFrom(oldPosition2);
  76144. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76145. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76146. object.computeWorldMatrix(true);
  76147. break;
  76148. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76149. returnValue = new this.BJSCANNON.Particle();
  76150. break;
  76151. }
  76152. return returnValue;
  76153. };
  76154. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76155. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76156. var transform = object.computeWorldMatrix(true);
  76157. // convert rawVerts to object space
  76158. var temp = new Array();
  76159. var index;
  76160. for (index = 0; index < pos.length; index += 3) {
  76161. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76162. }
  76163. pos = temp;
  76164. var matrix = new Array();
  76165. //For now pointDepth will not be used and will be automatically calculated.
  76166. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76167. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76168. var boundingInfo = object.getBoundingInfo();
  76169. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76170. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76171. var elementSize = dim * 2 / arraySize;
  76172. for (var i = 0; i < pos.length; i = i + 3) {
  76173. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76174. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76175. var y = -pos[i + 2] + minY;
  76176. if (!matrix[x]) {
  76177. matrix[x] = [];
  76178. }
  76179. if (!matrix[x][z]) {
  76180. matrix[x][z] = y;
  76181. }
  76182. matrix[x][z] = Math.max(y, matrix[x][z]);
  76183. }
  76184. for (var x = 0; x <= arraySize; ++x) {
  76185. if (!matrix[x]) {
  76186. var loc = 1;
  76187. while (!matrix[(x + loc) % arraySize]) {
  76188. loc++;
  76189. }
  76190. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76191. //console.log("missing x", x);
  76192. }
  76193. for (var z = 0; z <= arraySize; ++z) {
  76194. if (!matrix[x][z]) {
  76195. var loc = 1;
  76196. var newValue;
  76197. while (newValue === undefined) {
  76198. newValue = matrix[x][(z + loc++) % arraySize];
  76199. }
  76200. matrix[x][z] = newValue;
  76201. }
  76202. }
  76203. }
  76204. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76205. elementSize: elementSize
  76206. });
  76207. //For future reference, needed for body transformation
  76208. shape.minY = minY;
  76209. return shape;
  76210. };
  76211. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76212. var object = impostor.object;
  76213. //make sure it is updated...
  76214. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76215. // The delta between the mesh position and the mesh bounding box center
  76216. var bInfo = object.getBoundingInfo();
  76217. if (!bInfo)
  76218. return;
  76219. var center = impostor.getObjectCenter();
  76220. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76221. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76222. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76223. this._tmpPosition.copyFrom(center);
  76224. var quaternion = object.rotationQuaternion;
  76225. if (!quaternion) {
  76226. return;
  76227. }
  76228. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76229. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76230. //-90 DEG in X, precalculated
  76231. quaternion = quaternion.multiply(this._minus90X);
  76232. //Invert! (Precalculated, 90 deg in X)
  76233. //No need to clone. this will never change.
  76234. impostor.setDeltaRotation(this._plus90X);
  76235. }
  76236. //If it is a heightfield, if should be centered.
  76237. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76238. var mesh = object;
  76239. var boundingInfo = mesh.getBoundingInfo();
  76240. //calculate the correct body position:
  76241. var rotationQuaternion = mesh.rotationQuaternion;
  76242. mesh.rotationQuaternion = this._tmpUnityRotation;
  76243. mesh.computeWorldMatrix(true);
  76244. //get original center with no rotation
  76245. var c = center.clone();
  76246. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76247. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76248. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76249. mesh.setPreTransformMatrix(p);
  76250. mesh.computeWorldMatrix(true);
  76251. //calculate the translation
  76252. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76253. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76254. //add it inverted to the delta
  76255. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76256. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76257. //rotation is back
  76258. mesh.rotationQuaternion = rotationQuaternion;
  76259. mesh.setPreTransformMatrix(oldPivot);
  76260. mesh.computeWorldMatrix(true);
  76261. }
  76262. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76263. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76264. //this._tmpPosition.copyFrom(object.position);
  76265. }
  76266. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76267. //Now update the impostor object
  76268. impostor.physicsBody.position.copy(this._tmpPosition);
  76269. impostor.physicsBody.quaternion.copy(quaternion);
  76270. };
  76271. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76272. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76273. if (impostor.object.rotationQuaternion) {
  76274. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76275. }
  76276. };
  76277. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76278. impostor.physicsBody.position.copy(newPosition);
  76279. impostor.physicsBody.quaternion.copy(newRotation);
  76280. };
  76281. CannonJSPlugin.prototype.isSupported = function () {
  76282. return this.BJSCANNON !== undefined;
  76283. };
  76284. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76285. impostor.physicsBody.velocity.copy(velocity);
  76286. };
  76287. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76288. impostor.physicsBody.angularVelocity.copy(velocity);
  76289. };
  76290. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76291. var v = impostor.physicsBody.velocity;
  76292. if (!v) {
  76293. return null;
  76294. }
  76295. return new BABYLON.Vector3(v.x, v.y, v.z);
  76296. };
  76297. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76298. var v = impostor.physicsBody.angularVelocity;
  76299. if (!v) {
  76300. return null;
  76301. }
  76302. return new BABYLON.Vector3(v.x, v.y, v.z);
  76303. };
  76304. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76305. impostor.physicsBody.mass = mass;
  76306. impostor.physicsBody.updateMassProperties();
  76307. };
  76308. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76309. return impostor.physicsBody.mass;
  76310. };
  76311. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76312. return impostor.physicsBody.material.friction;
  76313. };
  76314. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76315. impostor.physicsBody.material.friction = friction;
  76316. };
  76317. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76318. return impostor.physicsBody.material.restitution;
  76319. };
  76320. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76321. impostor.physicsBody.material.restitution = restitution;
  76322. };
  76323. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76324. impostor.physicsBody.sleep();
  76325. };
  76326. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76327. impostor.physicsBody.wakeUp();
  76328. };
  76329. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76330. joint.physicsJoint.distance = maxDistance;
  76331. };
  76332. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76333. // if (!motorIndex) {
  76334. // joint.physicsJoint.enableMotor();
  76335. // }
  76336. // }
  76337. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76338. // if (!motorIndex) {
  76339. // joint.physicsJoint.disableMotor();
  76340. // }
  76341. // }
  76342. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76343. if (!motorIndex) {
  76344. joint.physicsJoint.enableMotor();
  76345. joint.physicsJoint.setMotorSpeed(speed);
  76346. if (maxForce) {
  76347. this.setLimit(joint, maxForce);
  76348. }
  76349. }
  76350. };
  76351. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76352. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76353. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76354. };
  76355. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76356. var body = impostor.physicsBody;
  76357. mesh.position.x = body.position.x;
  76358. mesh.position.y = body.position.y;
  76359. mesh.position.z = body.position.z;
  76360. if (mesh.rotationQuaternion) {
  76361. mesh.rotationQuaternion.x = body.quaternion.x;
  76362. mesh.rotationQuaternion.y = body.quaternion.y;
  76363. mesh.rotationQuaternion.z = body.quaternion.z;
  76364. mesh.rotationQuaternion.w = body.quaternion.w;
  76365. }
  76366. };
  76367. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76368. var shape = impostor.physicsBody.shapes[0];
  76369. return shape.boundingSphereRadius;
  76370. };
  76371. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76372. var shape = impostor.physicsBody.shapes[0];
  76373. result.x = shape.halfExtents.x * 2;
  76374. result.y = shape.halfExtents.y * 2;
  76375. result.z = shape.halfExtents.z * 2;
  76376. };
  76377. CannonJSPlugin.prototype.dispose = function () {
  76378. };
  76379. CannonJSPlugin.prototype._extendNamespace = function () {
  76380. //this will force cannon to execute at least one step when using interpolation
  76381. var step_tmp1 = new this.BJSCANNON.Vec3();
  76382. var Engine = this.BJSCANNON;
  76383. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76384. maxSubSteps = maxSubSteps || 10;
  76385. timeSinceLastCalled = timeSinceLastCalled || 0;
  76386. if (timeSinceLastCalled === 0) {
  76387. this.internalStep(dt);
  76388. this.time += dt;
  76389. }
  76390. else {
  76391. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76392. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76393. var t0 = performance.now();
  76394. for (var i = 0; i !== internalSteps; i++) {
  76395. this.internalStep(dt);
  76396. if (performance.now() - t0 > dt * 1000) {
  76397. break;
  76398. }
  76399. }
  76400. this.time += timeSinceLastCalled;
  76401. var h = this.time % dt;
  76402. var h_div_dt = h / dt;
  76403. var interpvelo = step_tmp1;
  76404. var bodies = this.bodies;
  76405. for (var j = 0; j !== bodies.length; j++) {
  76406. var b = bodies[j];
  76407. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76408. b.position.vsub(b.previousPosition, interpvelo);
  76409. interpvelo.scale(h_div_dt, interpvelo);
  76410. b.position.vadd(interpvelo, b.interpolatedPosition);
  76411. }
  76412. else {
  76413. b.interpolatedPosition.copy(b.position);
  76414. b.interpolatedQuaternion.copy(b.quaternion);
  76415. }
  76416. }
  76417. }
  76418. };
  76419. };
  76420. return CannonJSPlugin;
  76421. }());
  76422. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76423. })(BABYLON || (BABYLON = {}));
  76424. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76425. var BABYLON;
  76426. (function (BABYLON) {
  76427. var OimoJSPlugin = /** @class */ (function () {
  76428. function OimoJSPlugin(iterations) {
  76429. this.name = "OimoJSPlugin";
  76430. this._tmpImpostorsArray = [];
  76431. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76432. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76433. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76434. this.world.worldscale(1);
  76435. this.world.clear();
  76436. //making sure no stats are calculated
  76437. this.world.isNoStat = true;
  76438. }
  76439. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76440. this.world.gravity.copy(gravity);
  76441. };
  76442. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76443. this.world.timeStep = timeStep;
  76444. };
  76445. OimoJSPlugin.prototype.getTimeStep = function () {
  76446. return this.world.timeStep;
  76447. };
  76448. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76449. var _this = this;
  76450. impostors.forEach(function (impostor) {
  76451. impostor.beforeStep();
  76452. });
  76453. this.world.step();
  76454. impostors.forEach(function (impostor) {
  76455. impostor.afterStep();
  76456. //update the ordered impostors array
  76457. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76458. });
  76459. //check for collisions
  76460. var contact = this.world.contacts;
  76461. while (contact !== null) {
  76462. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76463. contact = contact.next;
  76464. continue;
  76465. }
  76466. //is this body colliding with any other? get the impostor
  76467. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76468. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76469. if (!mainImpostor || !collidingImpostor) {
  76470. contact = contact.next;
  76471. continue;
  76472. }
  76473. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76474. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76475. contact = contact.next;
  76476. }
  76477. };
  76478. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76479. var mass = impostor.physicsBody.massInfo.mass;
  76480. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76481. };
  76482. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76483. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76484. this.applyImpulse(impostor, force, contactPoint);
  76485. };
  76486. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76487. var _this = this;
  76488. //parent-child relationship. Does this impostor has a parent impostor?
  76489. if (impostor.parent) {
  76490. if (impostor.physicsBody) {
  76491. this.removePhysicsBody(impostor);
  76492. //TODO is that needed?
  76493. impostor.forceUpdate();
  76494. }
  76495. return;
  76496. }
  76497. if (impostor.isBodyInitRequired()) {
  76498. var bodyConfig = {
  76499. name: impostor.uniqueId,
  76500. //Oimo must have mass, also for static objects.
  76501. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76502. size: [],
  76503. type: [],
  76504. pos: [],
  76505. rot: [],
  76506. move: impostor.getParam("mass") !== 0,
  76507. //Supporting older versions of Oimo
  76508. world: this.world
  76509. };
  76510. var impostors = [impostor];
  76511. var addToArray = function (parent) {
  76512. if (!parent.getChildMeshes)
  76513. return;
  76514. parent.getChildMeshes().forEach(function (m) {
  76515. if (m.physicsImpostor) {
  76516. impostors.push(m.physicsImpostor);
  76517. //m.physicsImpostor._init();
  76518. }
  76519. });
  76520. };
  76521. addToArray(impostor.object);
  76522. var checkWithEpsilon_1 = function (value) {
  76523. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76524. };
  76525. impostors.forEach(function (i) {
  76526. if (!impostor.object.rotationQuaternion) {
  76527. return;
  76528. }
  76529. //get the correct bounding box
  76530. var oldQuaternion = i.object.rotationQuaternion;
  76531. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76532. x: impostor.object.rotationQuaternion.x,
  76533. y: impostor.object.rotationQuaternion.y,
  76534. z: impostor.object.rotationQuaternion.z,
  76535. s: impostor.object.rotationQuaternion.w
  76536. });
  76537. var extendSize = i.getObjectExtendSize();
  76538. if (i === impostor) {
  76539. var center = impostor.getObjectCenter();
  76540. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76541. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76542. //Can also use Array.prototype.push.apply
  76543. bodyConfig.pos.push(center.x);
  76544. bodyConfig.pos.push(center.y);
  76545. bodyConfig.pos.push(center.z);
  76546. //tmp solution
  76547. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76548. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76549. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76550. }
  76551. else {
  76552. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76553. bodyConfig.pos.push(localPosition.x);
  76554. bodyConfig.pos.push(localPosition.y);
  76555. bodyConfig.pos.push(localPosition.z);
  76556. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76557. bodyConfig.rot.push(0);
  76558. bodyConfig.rot.push(0);
  76559. bodyConfig.rot.push(0);
  76560. }
  76561. // register mesh
  76562. switch (i.type) {
  76563. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76564. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76565. case BABYLON.PhysicsImpostor.SphereImpostor:
  76566. var radiusX = extendSize.x;
  76567. var radiusY = extendSize.y;
  76568. var radiusZ = extendSize.z;
  76569. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76570. bodyConfig.type.push('sphere');
  76571. //due to the way oimo works with compounds, add 3 times
  76572. bodyConfig.size.push(size);
  76573. bodyConfig.size.push(size);
  76574. bodyConfig.size.push(size);
  76575. break;
  76576. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76577. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76578. var sizeY = checkWithEpsilon_1(extendSize.y);
  76579. bodyConfig.type.push('cylinder');
  76580. bodyConfig.size.push(sizeX);
  76581. bodyConfig.size.push(sizeY);
  76582. //due to the way oimo works with compounds, add one more value.
  76583. bodyConfig.size.push(sizeY);
  76584. break;
  76585. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76586. case BABYLON.PhysicsImpostor.BoxImpostor:
  76587. default:
  76588. var sizeX = checkWithEpsilon_1(extendSize.x);
  76589. var sizeY = checkWithEpsilon_1(extendSize.y);
  76590. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76591. bodyConfig.type.push('box');
  76592. bodyConfig.size.push(sizeX);
  76593. bodyConfig.size.push(sizeY);
  76594. bodyConfig.size.push(sizeZ);
  76595. break;
  76596. }
  76597. //actually not needed, but hey...
  76598. i.object.rotationQuaternion = oldQuaternion;
  76599. });
  76600. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76601. }
  76602. else {
  76603. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76604. }
  76605. impostor.setDeltaPosition(this._tmpPositionVector);
  76606. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76607. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76608. };
  76609. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76610. //impostor.physicsBody.dispose();
  76611. //Same as : (older oimo versions)
  76612. this.world.removeRigidBody(impostor.physicsBody);
  76613. };
  76614. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76615. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76616. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76617. if (!mainBody || !connectedBody) {
  76618. return;
  76619. }
  76620. var jointData = impostorJoint.joint.jointData;
  76621. var options = jointData.nativeParams || {};
  76622. var type;
  76623. var nativeJointData = {
  76624. body1: mainBody,
  76625. body2: connectedBody,
  76626. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76627. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76628. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76629. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76630. min: options.min,
  76631. max: options.max,
  76632. collision: options.collision || jointData.collision,
  76633. spring: options.spring,
  76634. //supporting older version of Oimo
  76635. world: this.world
  76636. };
  76637. switch (impostorJoint.joint.type) {
  76638. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76639. type = "jointBall";
  76640. break;
  76641. case BABYLON.PhysicsJoint.SpringJoint:
  76642. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76643. var springData = jointData;
  76644. nativeJointData.min = springData.length || nativeJointData.min;
  76645. //Max should also be set, just make sure it is at least min
  76646. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76647. case BABYLON.PhysicsJoint.DistanceJoint:
  76648. type = "jointDistance";
  76649. nativeJointData.max = jointData.maxDistance;
  76650. break;
  76651. case BABYLON.PhysicsJoint.PrismaticJoint:
  76652. type = "jointPrisme";
  76653. break;
  76654. case BABYLON.PhysicsJoint.SliderJoint:
  76655. type = "jointSlide";
  76656. break;
  76657. case BABYLON.PhysicsJoint.WheelJoint:
  76658. type = "jointWheel";
  76659. break;
  76660. case BABYLON.PhysicsJoint.HingeJoint:
  76661. default:
  76662. type = "jointHinge";
  76663. break;
  76664. }
  76665. nativeJointData.type = type;
  76666. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76667. };
  76668. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76669. //Bug in Oimo prevents us from disposing a joint in the playground
  76670. //joint.joint.physicsJoint.dispose();
  76671. //So we will bruteforce it!
  76672. try {
  76673. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76674. }
  76675. catch (e) {
  76676. BABYLON.Tools.Warn(e);
  76677. }
  76678. };
  76679. OimoJSPlugin.prototype.isSupported = function () {
  76680. return this.BJSOIMO !== undefined;
  76681. };
  76682. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76683. if (!impostor.physicsBody.sleeping) {
  76684. //TODO check that
  76685. if (impostor.physicsBody.shapes.next) {
  76686. var parentShape = this._getLastShape(impostor.physicsBody);
  76687. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76688. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76689. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76690. }
  76691. else {
  76692. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76693. }
  76694. if (impostor.object.rotationQuaternion) {
  76695. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76696. impostor.object.rotationQuaternion.normalize();
  76697. }
  76698. }
  76699. };
  76700. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76701. var body = impostor.physicsBody;
  76702. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76703. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76704. body.syncShapes();
  76705. body.awake();
  76706. };
  76707. OimoJSPlugin.prototype._getLastShape = function (body) {
  76708. var lastShape = body.shapes;
  76709. while (lastShape.next) {
  76710. lastShape = lastShape.next;
  76711. }
  76712. return lastShape;
  76713. };
  76714. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76715. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76716. };
  76717. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76718. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76719. };
  76720. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76721. var v = impostor.physicsBody.linearVelocity;
  76722. if (!v) {
  76723. return null;
  76724. }
  76725. return new BABYLON.Vector3(v.x, v.y, v.z);
  76726. };
  76727. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76728. var v = impostor.physicsBody.angularVelocity;
  76729. if (!v) {
  76730. return null;
  76731. }
  76732. return new BABYLON.Vector3(v.x, v.y, v.z);
  76733. };
  76734. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76735. var staticBody = mass === 0;
  76736. //this will actually set the body's density and not its mass.
  76737. //But this is how oimo treats the mass variable.
  76738. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76739. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76740. };
  76741. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76742. return impostor.physicsBody.shapes.density;
  76743. };
  76744. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76745. return impostor.physicsBody.shapes.friction;
  76746. };
  76747. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76748. impostor.physicsBody.shapes.friction = friction;
  76749. };
  76750. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76751. return impostor.physicsBody.shapes.restitution;
  76752. };
  76753. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76754. impostor.physicsBody.shapes.restitution = restitution;
  76755. };
  76756. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76757. impostor.physicsBody.sleep();
  76758. };
  76759. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76760. impostor.physicsBody.awake();
  76761. };
  76762. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76763. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76764. if (minDistance !== void 0) {
  76765. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76766. }
  76767. };
  76768. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76769. //TODO separate rotational and transational motors.
  76770. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76771. if (motor) {
  76772. motor.setMotor(speed, maxForce);
  76773. }
  76774. };
  76775. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76776. //TODO separate rotational and transational motors.
  76777. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76778. if (motor) {
  76779. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76780. }
  76781. };
  76782. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76783. var body = impostor.physicsBody;
  76784. mesh.position.x = body.position.x;
  76785. mesh.position.y = body.position.y;
  76786. mesh.position.z = body.position.z;
  76787. if (mesh.rotationQuaternion) {
  76788. mesh.rotationQuaternion.x = body.orientation.x;
  76789. mesh.rotationQuaternion.y = body.orientation.y;
  76790. mesh.rotationQuaternion.z = body.orientation.z;
  76791. mesh.rotationQuaternion.w = body.orientation.s;
  76792. }
  76793. };
  76794. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76795. return impostor.physicsBody.shapes.radius;
  76796. };
  76797. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76798. var shape = impostor.physicsBody.shapes;
  76799. result.x = shape.halfWidth * 2;
  76800. result.y = shape.halfHeight * 2;
  76801. result.z = shape.halfDepth * 2;
  76802. };
  76803. OimoJSPlugin.prototype.dispose = function () {
  76804. this.world.clear();
  76805. };
  76806. return OimoJSPlugin;
  76807. }());
  76808. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76809. })(BABYLON || (BABYLON = {}));
  76810. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76811. var BABYLON;
  76812. (function (BABYLON) {
  76813. /*
  76814. * Based on jsTGALoader - Javascript loader for TGA file
  76815. * By Vincent Thibault
  76816. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76817. */
  76818. var TGATools = /** @class */ (function () {
  76819. function TGATools() {
  76820. }
  76821. TGATools.GetTGAHeader = function (data) {
  76822. var offset = 0;
  76823. var header = {
  76824. id_length: data[offset++],
  76825. colormap_type: data[offset++],
  76826. image_type: data[offset++],
  76827. colormap_index: data[offset++] | data[offset++] << 8,
  76828. colormap_length: data[offset++] | data[offset++] << 8,
  76829. colormap_size: data[offset++],
  76830. origin: [
  76831. data[offset++] | data[offset++] << 8,
  76832. data[offset++] | data[offset++] << 8
  76833. ],
  76834. width: data[offset++] | data[offset++] << 8,
  76835. height: data[offset++] | data[offset++] << 8,
  76836. pixel_size: data[offset++],
  76837. flags: data[offset++]
  76838. };
  76839. return header;
  76840. };
  76841. TGATools.UploadContent = function (gl, data) {
  76842. // Not enough data to contain header ?
  76843. if (data.length < 19) {
  76844. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76845. return;
  76846. }
  76847. // Read Header
  76848. var offset = 18;
  76849. var header = TGATools.GetTGAHeader(data);
  76850. // Assume it's a valid Targa file.
  76851. if (header.id_length + offset > data.length) {
  76852. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76853. return;
  76854. }
  76855. // Skip not needed data
  76856. offset += header.id_length;
  76857. var use_rle = false;
  76858. var use_pal = false;
  76859. var use_grey = false;
  76860. // Get some informations.
  76861. switch (header.image_type) {
  76862. case TGATools._TYPE_RLE_INDEXED:
  76863. use_rle = true;
  76864. case TGATools._TYPE_INDEXED:
  76865. use_pal = true;
  76866. break;
  76867. case TGATools._TYPE_RLE_RGB:
  76868. use_rle = true;
  76869. case TGATools._TYPE_RGB:
  76870. // use_rgb = true;
  76871. break;
  76872. case TGATools._TYPE_RLE_GREY:
  76873. use_rle = true;
  76874. case TGATools._TYPE_GREY:
  76875. use_grey = true;
  76876. break;
  76877. }
  76878. var pixel_data;
  76879. // var numAlphaBits = header.flags & 0xf;
  76880. var pixel_size = header.pixel_size >> 3;
  76881. var pixel_total = header.width * header.height * pixel_size;
  76882. // Read palettes
  76883. var palettes;
  76884. if (use_pal) {
  76885. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76886. }
  76887. // Read LRE
  76888. if (use_rle) {
  76889. pixel_data = new Uint8Array(pixel_total);
  76890. var c, count, i;
  76891. var localOffset = 0;
  76892. var pixels = new Uint8Array(pixel_size);
  76893. while (offset < pixel_total && localOffset < pixel_total) {
  76894. c = data[offset++];
  76895. count = (c & 0x7f) + 1;
  76896. // RLE pixels
  76897. if (c & 0x80) {
  76898. // Bind pixel tmp array
  76899. for (i = 0; i < pixel_size; ++i) {
  76900. pixels[i] = data[offset++];
  76901. }
  76902. // Copy pixel array
  76903. for (i = 0; i < count; ++i) {
  76904. pixel_data.set(pixels, localOffset + i * pixel_size);
  76905. }
  76906. localOffset += pixel_size * count;
  76907. }
  76908. else {
  76909. count *= pixel_size;
  76910. for (i = 0; i < count; ++i) {
  76911. pixel_data[localOffset + i] = data[offset++];
  76912. }
  76913. localOffset += count;
  76914. }
  76915. }
  76916. }
  76917. else {
  76918. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76919. }
  76920. // Load to texture
  76921. var x_start, y_start, x_step, y_step, y_end, x_end;
  76922. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76923. default:
  76924. case TGATools._ORIGIN_UL:
  76925. x_start = 0;
  76926. x_step = 1;
  76927. x_end = header.width;
  76928. y_start = 0;
  76929. y_step = 1;
  76930. y_end = header.height;
  76931. break;
  76932. case TGATools._ORIGIN_BL:
  76933. x_start = 0;
  76934. x_step = 1;
  76935. x_end = header.width;
  76936. y_start = header.height - 1;
  76937. y_step = -1;
  76938. y_end = -1;
  76939. break;
  76940. case TGATools._ORIGIN_UR:
  76941. x_start = header.width - 1;
  76942. x_step = -1;
  76943. x_end = -1;
  76944. y_start = 0;
  76945. y_step = 1;
  76946. y_end = header.height;
  76947. break;
  76948. case TGATools._ORIGIN_BR:
  76949. x_start = header.width - 1;
  76950. x_step = -1;
  76951. x_end = -1;
  76952. y_start = header.height - 1;
  76953. y_step = -1;
  76954. y_end = -1;
  76955. break;
  76956. }
  76957. // Load the specify method
  76958. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76959. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76960. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76961. };
  76962. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76963. var image = pixel_data, colormap = palettes;
  76964. var width = header.width, height = header.height;
  76965. var color, i = 0, x, y;
  76966. var imageData = new Uint8Array(width * height * 4);
  76967. for (y = y_start; y !== y_end; y += y_step) {
  76968. for (x = x_start; x !== x_end; x += x_step, i++) {
  76969. color = image[i];
  76970. imageData[(x + width * y) * 4 + 3] = 255;
  76971. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76972. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76973. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76974. }
  76975. }
  76976. return imageData;
  76977. };
  76978. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76979. var image = pixel_data;
  76980. var width = header.width, height = header.height;
  76981. var color, i = 0, x, y;
  76982. var imageData = new Uint8Array(width * height * 4);
  76983. for (y = y_start; y !== y_end; y += y_step) {
  76984. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76985. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76986. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76987. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76988. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76989. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76990. }
  76991. }
  76992. return imageData;
  76993. };
  76994. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76995. var image = pixel_data;
  76996. var width = header.width, height = header.height;
  76997. var i = 0, x, y;
  76998. var imageData = new Uint8Array(width * height * 4);
  76999. for (y = y_start; y !== y_end; y += y_step) {
  77000. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77001. imageData[(x + width * y) * 4 + 3] = 255;
  77002. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77003. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77004. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77005. }
  77006. }
  77007. return imageData;
  77008. };
  77009. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77010. var image = pixel_data;
  77011. var width = header.width, height = header.height;
  77012. var i = 0, x, y;
  77013. var imageData = new Uint8Array(width * height * 4);
  77014. for (y = y_start; y !== y_end; y += y_step) {
  77015. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77016. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77017. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77018. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77019. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77020. }
  77021. }
  77022. return imageData;
  77023. };
  77024. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77025. var image = pixel_data;
  77026. var width = header.width, height = header.height;
  77027. var color, i = 0, x, y;
  77028. var imageData = new Uint8Array(width * height * 4);
  77029. for (y = y_start; y !== y_end; y += y_step) {
  77030. for (x = x_start; x !== x_end; x += x_step, i++) {
  77031. color = image[i];
  77032. imageData[(x + width * y) * 4 + 0] = color;
  77033. imageData[(x + width * y) * 4 + 1] = color;
  77034. imageData[(x + width * y) * 4 + 2] = color;
  77035. imageData[(x + width * y) * 4 + 3] = 255;
  77036. }
  77037. }
  77038. return imageData;
  77039. };
  77040. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77041. var image = pixel_data;
  77042. var width = header.width, height = header.height;
  77043. var i = 0, x, y;
  77044. var imageData = new Uint8Array(width * height * 4);
  77045. for (y = y_start; y !== y_end; y += y_step) {
  77046. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77047. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77048. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77049. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77050. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77051. }
  77052. }
  77053. return imageData;
  77054. };
  77055. //private static _TYPE_NO_DATA = 0;
  77056. TGATools._TYPE_INDEXED = 1;
  77057. TGATools._TYPE_RGB = 2;
  77058. TGATools._TYPE_GREY = 3;
  77059. TGATools._TYPE_RLE_INDEXED = 9;
  77060. TGATools._TYPE_RLE_RGB = 10;
  77061. TGATools._TYPE_RLE_GREY = 11;
  77062. TGATools._ORIGIN_MASK = 0x30;
  77063. TGATools._ORIGIN_SHIFT = 0x04;
  77064. TGATools._ORIGIN_BL = 0x00;
  77065. TGATools._ORIGIN_BR = 0x01;
  77066. TGATools._ORIGIN_UL = 0x02;
  77067. TGATools._ORIGIN_UR = 0x03;
  77068. return TGATools;
  77069. }());
  77070. BABYLON.TGATools = TGATools;
  77071. })(BABYLON || (BABYLON = {}));
  77072. //# sourceMappingURL=babylon.tga.js.map
  77073. var BABYLON;
  77074. (function (BABYLON) {
  77075. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77076. // All values and structures referenced from:
  77077. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77078. var DDS_MAGIC = 0x20534444;
  77079. var
  77080. //DDSD_CAPS = 0x1,
  77081. //DDSD_HEIGHT = 0x2,
  77082. //DDSD_WIDTH = 0x4,
  77083. //DDSD_PITCH = 0x8,
  77084. //DDSD_PIXELFORMAT = 0x1000,
  77085. DDSD_MIPMAPCOUNT = 0x20000;
  77086. //DDSD_LINEARSIZE = 0x80000,
  77087. //DDSD_DEPTH = 0x800000;
  77088. // var DDSCAPS_COMPLEX = 0x8,
  77089. // DDSCAPS_MIPMAP = 0x400000,
  77090. // DDSCAPS_TEXTURE = 0x1000;
  77091. var DDSCAPS2_CUBEMAP = 0x200;
  77092. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77093. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77094. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77095. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77096. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77097. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77098. // DDSCAPS2_VOLUME = 0x200000;
  77099. var
  77100. //DDPF_ALPHAPIXELS = 0x1,
  77101. //DDPF_ALPHA = 0x2,
  77102. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77103. //DDPF_YUV = 0x200,
  77104. DDPF_LUMINANCE = 0x20000;
  77105. function FourCCToInt32(value) {
  77106. return value.charCodeAt(0) +
  77107. (value.charCodeAt(1) << 8) +
  77108. (value.charCodeAt(2) << 16) +
  77109. (value.charCodeAt(3) << 24);
  77110. }
  77111. function Int32ToFourCC(value) {
  77112. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77113. }
  77114. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77115. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77116. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77117. var FOURCC_DX10 = FourCCToInt32("DX10");
  77118. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77119. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77120. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77121. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77122. var headerLengthInt = 31; // The header length in 32 bit ints
  77123. // Offsets into the header array
  77124. var off_magic = 0;
  77125. var off_size = 1;
  77126. var off_flags = 2;
  77127. var off_height = 3;
  77128. var off_width = 4;
  77129. var off_mipmapCount = 7;
  77130. var off_pfFlags = 20;
  77131. var off_pfFourCC = 21;
  77132. var off_RGBbpp = 22;
  77133. var off_RMask = 23;
  77134. var off_GMask = 24;
  77135. var off_BMask = 25;
  77136. var off_AMask = 26;
  77137. // var off_caps1 = 27;
  77138. var off_caps2 = 28;
  77139. // var off_caps3 = 29;
  77140. // var off_caps4 = 30;
  77141. var off_dxgiFormat = 32;
  77142. ;
  77143. var DDSTools = /** @class */ (function () {
  77144. function DDSTools() {
  77145. }
  77146. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77147. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77148. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77149. var mipmapCount = 1;
  77150. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77151. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77152. }
  77153. var fourCC = header[off_pfFourCC];
  77154. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77155. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77156. switch (fourCC) {
  77157. case FOURCC_D3DFMT_R16G16B16A16F:
  77158. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77159. break;
  77160. case FOURCC_D3DFMT_R32G32B32A32F:
  77161. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77162. break;
  77163. case FOURCC_DX10:
  77164. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77165. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77166. break;
  77167. }
  77168. }
  77169. return {
  77170. width: header[off_width],
  77171. height: header[off_height],
  77172. mipmapCount: mipmapCount,
  77173. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77174. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77175. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77176. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77177. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77178. dxgiFormat: dxgiFormat,
  77179. textureType: textureType
  77180. };
  77181. };
  77182. DDSTools._ToHalfFloat = function (value) {
  77183. if (!DDSTools._FloatView) {
  77184. DDSTools._FloatView = new Float32Array(1);
  77185. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77186. }
  77187. DDSTools._FloatView[0] = value;
  77188. var x = DDSTools._Int32View[0];
  77189. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77190. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77191. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77192. /* If zero, or denormal, or exponent underflows too much for a denormal
  77193. * half, return signed zero. */
  77194. if (e < 103) {
  77195. return bits;
  77196. }
  77197. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77198. if (e > 142) {
  77199. bits |= 0x7c00;
  77200. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77201. * not Inf, so make sure we set one mantissa bit too. */
  77202. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77203. return bits;
  77204. }
  77205. /* If exponent underflows but not too much, return a denormal */
  77206. if (e < 113) {
  77207. m |= 0x0800;
  77208. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77209. * to 1, which is OK. */
  77210. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77211. return bits;
  77212. }
  77213. bits |= ((e - 112) << 10) | (m >> 1);
  77214. bits += m & 1;
  77215. return bits;
  77216. };
  77217. DDSTools._FromHalfFloat = function (value) {
  77218. var s = (value & 0x8000) >> 15;
  77219. var e = (value & 0x7C00) >> 10;
  77220. var f = value & 0x03FF;
  77221. if (e === 0) {
  77222. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77223. }
  77224. else if (e == 0x1F) {
  77225. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77226. }
  77227. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77228. };
  77229. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77230. var destArray = new Float32Array(dataLength);
  77231. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77232. var index = 0;
  77233. for (var y = 0; y < height; y++) {
  77234. for (var x = 0; x < width; x++) {
  77235. var srcPos = (x + y * width) * 4;
  77236. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77237. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77238. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77239. if (DDSTools.StoreLODInAlphaChannel) {
  77240. destArray[index + 3] = lod;
  77241. }
  77242. else {
  77243. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77244. }
  77245. index += 4;
  77246. }
  77247. }
  77248. return destArray;
  77249. };
  77250. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77251. if (DDSTools.StoreLODInAlphaChannel) {
  77252. var destArray = new Uint16Array(dataLength);
  77253. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77254. var index = 0;
  77255. for (var y = 0; y < height; y++) {
  77256. for (var x = 0; x < width; x++) {
  77257. var srcPos = (x + y * width) * 4;
  77258. destArray[index] = srcData[srcPos];
  77259. destArray[index + 1] = srcData[srcPos + 1];
  77260. destArray[index + 2] = srcData[srcPos + 2];
  77261. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77262. index += 4;
  77263. }
  77264. }
  77265. return destArray;
  77266. }
  77267. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77268. };
  77269. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77270. if (DDSTools.StoreLODInAlphaChannel) {
  77271. var destArray = new Float32Array(dataLength);
  77272. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77273. var index = 0;
  77274. for (var y = 0; y < height; y++) {
  77275. for (var x = 0; x < width; x++) {
  77276. var srcPos = (x + y * width) * 4;
  77277. destArray[index] = srcData[srcPos];
  77278. destArray[index + 1] = srcData[srcPos + 1];
  77279. destArray[index + 2] = srcData[srcPos + 2];
  77280. destArray[index + 3] = lod;
  77281. index += 4;
  77282. }
  77283. }
  77284. return destArray;
  77285. }
  77286. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77287. };
  77288. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77289. var destArray = new Uint8Array(dataLength);
  77290. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77291. var index = 0;
  77292. for (var y = 0; y < height; y++) {
  77293. for (var x = 0; x < width; x++) {
  77294. var srcPos = (x + y * width) * 4;
  77295. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77296. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77297. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77298. if (DDSTools.StoreLODInAlphaChannel) {
  77299. destArray[index + 3] = lod;
  77300. }
  77301. else {
  77302. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77303. }
  77304. index += 4;
  77305. }
  77306. }
  77307. return destArray;
  77308. };
  77309. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77310. var destArray = new Uint8Array(dataLength);
  77311. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77312. var index = 0;
  77313. for (var y = 0; y < height; y++) {
  77314. for (var x = 0; x < width; x++) {
  77315. var srcPos = (x + y * width) * 4;
  77316. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77317. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77318. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77319. if (DDSTools.StoreLODInAlphaChannel) {
  77320. destArray[index + 3] = lod;
  77321. }
  77322. else {
  77323. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77324. }
  77325. index += 4;
  77326. }
  77327. }
  77328. return destArray;
  77329. };
  77330. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77331. var byteArray = new Uint8Array(dataLength);
  77332. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77333. var index = 0;
  77334. for (var y = 0; y < height; y++) {
  77335. for (var x = 0; x < width; x++) {
  77336. var srcPos = (x + y * width) * 4;
  77337. byteArray[index] = srcData[srcPos + rOffset];
  77338. byteArray[index + 1] = srcData[srcPos + gOffset];
  77339. byteArray[index + 2] = srcData[srcPos + bOffset];
  77340. byteArray[index + 3] = srcData[srcPos + aOffset];
  77341. index += 4;
  77342. }
  77343. }
  77344. return byteArray;
  77345. };
  77346. DDSTools._ExtractLongWordOrder = function (value) {
  77347. if (value === 0 || value === 255 || value === -16777216) {
  77348. return 0;
  77349. }
  77350. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77351. };
  77352. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77353. var byteArray = new Uint8Array(dataLength);
  77354. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77355. var index = 0;
  77356. for (var y = 0; y < height; y++) {
  77357. for (var x = 0; x < width; x++) {
  77358. var srcPos = (x + y * width) * 3;
  77359. byteArray[index] = srcData[srcPos + rOffset];
  77360. byteArray[index + 1] = srcData[srcPos + gOffset];
  77361. byteArray[index + 2] = srcData[srcPos + bOffset];
  77362. index += 3;
  77363. }
  77364. }
  77365. return byteArray;
  77366. };
  77367. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77368. var byteArray = new Uint8Array(dataLength);
  77369. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77370. var index = 0;
  77371. for (var y = 0; y < height; y++) {
  77372. for (var x = 0; x < width; x++) {
  77373. var srcPos = (x + y * width);
  77374. byteArray[index] = srcData[srcPos];
  77375. index++;
  77376. }
  77377. }
  77378. return byteArray;
  77379. };
  77380. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77381. if (lodIndex === void 0) { lodIndex = -1; }
  77382. var ext = engine.getCaps().s3tc;
  77383. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77384. var fourCC, width, height, dataLength = 0, dataOffset;
  77385. var byteArray, mipmapCount, mip;
  77386. var internalFormat = 0;
  77387. var format = 0;
  77388. var blockBytes = 1;
  77389. if (header[off_magic] !== DDS_MAGIC) {
  77390. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77391. return;
  77392. }
  77393. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77394. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77395. return;
  77396. }
  77397. if (info.isCompressed && !ext) {
  77398. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77399. return;
  77400. }
  77401. var bpp = header[off_RGBbpp];
  77402. dataOffset = header[off_size] + 4;
  77403. var computeFormats = false;
  77404. if (info.isFourCC) {
  77405. fourCC = header[off_pfFourCC];
  77406. switch (fourCC) {
  77407. case FOURCC_DXT1:
  77408. blockBytes = 8;
  77409. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77410. break;
  77411. case FOURCC_DXT3:
  77412. blockBytes = 16;
  77413. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77414. break;
  77415. case FOURCC_DXT5:
  77416. blockBytes = 16;
  77417. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77418. break;
  77419. case FOURCC_D3DFMT_R16G16B16A16F:
  77420. computeFormats = true;
  77421. break;
  77422. case FOURCC_D3DFMT_R32G32B32A32F:
  77423. computeFormats = true;
  77424. break;
  77425. case FOURCC_DX10:
  77426. // There is an additionnal header so dataOffset need to be changed
  77427. dataOffset += 5 * 4; // 5 uints
  77428. var supported = false;
  77429. switch (info.dxgiFormat) {
  77430. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77431. computeFormats = true;
  77432. supported = true;
  77433. break;
  77434. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77435. info.isRGB = true;
  77436. info.isFourCC = false;
  77437. bpp = 32;
  77438. supported = true;
  77439. break;
  77440. }
  77441. if (supported) {
  77442. break;
  77443. }
  77444. default:
  77445. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77446. return;
  77447. }
  77448. }
  77449. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77450. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77451. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77452. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77453. if (computeFormats) {
  77454. format = engine._getWebGLTextureType(info.textureType);
  77455. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77456. }
  77457. mipmapCount = 1;
  77458. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77459. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77460. }
  77461. for (var face = 0; face < faces; face++) {
  77462. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77463. width = header[off_width];
  77464. height = header[off_height];
  77465. for (mip = 0; mip < mipmapCount; ++mip) {
  77466. if (lodIndex === -1 || lodIndex === mip) {
  77467. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77468. var i = (lodIndex === -1) ? mip : 0;
  77469. if (!info.isCompressed && info.isFourCC) {
  77470. dataLength = width * height * 4;
  77471. var floatArray = null;
  77472. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77473. if (bpp === 128) {
  77474. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77475. }
  77476. else if (bpp === 64) {
  77477. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77478. }
  77479. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77480. format = engine._getWebGLTextureType(info.textureType);
  77481. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77482. }
  77483. else {
  77484. if (bpp === 128) {
  77485. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77486. }
  77487. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77488. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77489. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77490. format = engine._getWebGLTextureType(info.textureType);
  77491. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77492. }
  77493. else {
  77494. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77495. }
  77496. }
  77497. if (floatArray) {
  77498. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77499. }
  77500. }
  77501. else if (info.isRGB) {
  77502. if (bpp === 24) {
  77503. dataLength = width * height * 3;
  77504. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77505. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77506. }
  77507. else {
  77508. dataLength = width * height * 4;
  77509. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77510. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77511. }
  77512. }
  77513. else if (info.isLuminance) {
  77514. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77515. var unpaddedRowSize = width;
  77516. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77517. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77518. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77519. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77520. }
  77521. else {
  77522. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77523. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77524. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77525. }
  77526. }
  77527. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77528. width *= 0.5;
  77529. height *= 0.5;
  77530. width = Math.max(1.0, width);
  77531. height = Math.max(1.0, height);
  77532. }
  77533. if (currentFace !== undefined) {
  77534. // Loading a single face
  77535. break;
  77536. }
  77537. }
  77538. };
  77539. DDSTools.StoreLODInAlphaChannel = false;
  77540. return DDSTools;
  77541. }());
  77542. BABYLON.DDSTools = DDSTools;
  77543. })(BABYLON || (BABYLON = {}));
  77544. //# sourceMappingURL=babylon.dds.js.map
  77545. var BABYLON;
  77546. (function (BABYLON) {
  77547. /**
  77548. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77549. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77550. */
  77551. var KhronosTextureContainer = /** @class */ (function () {
  77552. /**
  77553. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77554. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77555. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77556. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77557. */
  77558. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77559. this.arrayBuffer = arrayBuffer;
  77560. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77561. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77562. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77563. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77564. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77565. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77566. BABYLON.Tools.Error("texture missing KTX identifier");
  77567. return;
  77568. }
  77569. // load the reset of the header in native 32 bit int
  77570. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77571. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77572. var oppositeEndianess = header[0] === 0x01020304;
  77573. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77574. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77575. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77576. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77577. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77578. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77579. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77580. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77581. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77582. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77583. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77584. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77585. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77586. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77587. if (this.glType !== 0) {
  77588. BABYLON.Tools.Error("only compressed formats currently supported");
  77589. return;
  77590. }
  77591. else {
  77592. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77593. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77594. }
  77595. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77596. BABYLON.Tools.Error("only 2D textures currently supported");
  77597. return;
  77598. }
  77599. if (this.numberOfArrayElements !== 0) {
  77600. BABYLON.Tools.Error("texture arrays not currently supported");
  77601. return;
  77602. }
  77603. if (this.numberOfFaces !== facesExpected) {
  77604. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77605. return;
  77606. }
  77607. // we now have a completely validated file, so could use existence of loadType as success
  77608. // would need to make this more elaborate & adjust checks above to support more than one load type
  77609. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77610. }
  77611. // not as fast hardware based, but will probably never need to use
  77612. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77613. return ((val & 0xFF) << 24)
  77614. | ((val & 0xFF00) << 8)
  77615. | ((val >> 8) & 0xFF00)
  77616. | ((val >> 24) & 0xFF);
  77617. };
  77618. /**
  77619. * It is assumed that the texture has already been created & is currently bound
  77620. */
  77621. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77622. switch (this.loadType) {
  77623. case KhronosTextureContainer.COMPRESSED_2D:
  77624. this._upload2DCompressedLevels(gl, loadMipmaps);
  77625. break;
  77626. case KhronosTextureContainer.TEX_2D:
  77627. case KhronosTextureContainer.COMPRESSED_3D:
  77628. case KhronosTextureContainer.TEX_3D:
  77629. }
  77630. };
  77631. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77632. // initialize width & height for level 1
  77633. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77634. var width = this.pixelWidth;
  77635. var height = this.pixelHeight;
  77636. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77637. for (var level = 0; level < mipmapCount; level++) {
  77638. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77639. for (var face = 0; face < this.numberOfFaces; face++) {
  77640. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77641. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77642. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77643. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77644. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77645. }
  77646. width = Math.max(1.0, width * 0.5);
  77647. height = Math.max(1.0, height * 0.5);
  77648. }
  77649. };
  77650. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77651. // load types
  77652. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77653. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77654. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77655. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77656. return KhronosTextureContainer;
  77657. }());
  77658. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77659. })(BABYLON || (BABYLON = {}));
  77660. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77661. var BABYLON;
  77662. (function (BABYLON) {
  77663. var Debug = /** @class */ (function () {
  77664. function Debug() {
  77665. }
  77666. Debug.AxesViewer = /** @class */ (function () {
  77667. function AxesViewer(scene, scaleLines) {
  77668. if (scaleLines === void 0) { scaleLines = 1; }
  77669. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77670. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77671. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77672. this.scaleLines = 1;
  77673. this.scaleLines = scaleLines;
  77674. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77675. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77676. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77677. this._xmesh.renderingGroupId = 2;
  77678. this._ymesh.renderingGroupId = 2;
  77679. this._zmesh.renderingGroupId = 2;
  77680. this._xmesh.material.checkReadyOnlyOnce = true;
  77681. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77682. this._ymesh.material.checkReadyOnlyOnce = true;
  77683. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77684. this._zmesh.material.checkReadyOnlyOnce = true;
  77685. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77686. this.scene = scene;
  77687. }
  77688. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77689. var scaleLines = this.scaleLines;
  77690. if (this._xmesh) {
  77691. this._xmesh.position.copyFrom(position);
  77692. }
  77693. if (this._ymesh) {
  77694. this._ymesh.position.copyFrom(position);
  77695. }
  77696. if (this._zmesh) {
  77697. this._zmesh.position.copyFrom(position);
  77698. }
  77699. var point2 = this._xline[1];
  77700. point2.x = xaxis.x * scaleLines;
  77701. point2.y = xaxis.y * scaleLines;
  77702. point2.z = xaxis.z * scaleLines;
  77703. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77704. point2 = this._yline[1];
  77705. point2.x = yaxis.x * scaleLines;
  77706. point2.y = yaxis.y * scaleLines;
  77707. point2.z = yaxis.z * scaleLines;
  77708. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77709. point2 = this._zline[1];
  77710. point2.x = zaxis.x * scaleLines;
  77711. point2.y = zaxis.y * scaleLines;
  77712. point2.z = zaxis.z * scaleLines;
  77713. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77714. };
  77715. AxesViewer.prototype.dispose = function () {
  77716. if (this._xmesh) {
  77717. this._xmesh.dispose();
  77718. }
  77719. if (this._ymesh) {
  77720. this._ymesh.dispose();
  77721. }
  77722. if (this._zmesh) {
  77723. this._zmesh.dispose();
  77724. }
  77725. this._xmesh = null;
  77726. this._ymesh = null;
  77727. this._zmesh = null;
  77728. this.scene = null;
  77729. };
  77730. return AxesViewer;
  77731. }());
  77732. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77733. __extends(BoneAxesViewer, _super);
  77734. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77735. if (scaleLines === void 0) { scaleLines = 1; }
  77736. var _this = _super.call(this, scene, scaleLines) || this;
  77737. _this.pos = BABYLON.Vector3.Zero();
  77738. _this.xaxis = BABYLON.Vector3.Zero();
  77739. _this.yaxis = BABYLON.Vector3.Zero();
  77740. _this.zaxis = BABYLON.Vector3.Zero();
  77741. _this.mesh = mesh;
  77742. _this.bone = bone;
  77743. return _this;
  77744. }
  77745. BoneAxesViewer.prototype.update = function () {
  77746. if (!this.mesh || !this.bone) {
  77747. return;
  77748. }
  77749. var bone = this.bone;
  77750. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77751. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77752. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77753. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77754. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77755. };
  77756. BoneAxesViewer.prototype.dispose = function () {
  77757. if (this.mesh) {
  77758. this.mesh = null;
  77759. this.bone = null;
  77760. _super.prototype.dispose.call(this);
  77761. }
  77762. };
  77763. return BoneAxesViewer;
  77764. }(Debug.AxesViewer));
  77765. Debug.PhysicsViewer = /** @class */ (function () {
  77766. function PhysicsViewer(scene) {
  77767. this._impostors = [];
  77768. this._meshes = [];
  77769. this._numMeshes = 0;
  77770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77771. var physicEngine = this._scene.getPhysicsEngine();
  77772. if (physicEngine) {
  77773. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77774. }
  77775. }
  77776. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77777. var plugin = this._physicsEnginePlugin;
  77778. for (var i = 0; i < this._numMeshes; i++) {
  77779. var impostor = this._impostors[i];
  77780. if (!impostor) {
  77781. continue;
  77782. }
  77783. if (impostor.isDisposed) {
  77784. this.hideImpostor(this._impostors[i--]);
  77785. }
  77786. else {
  77787. var mesh = this._meshes[i];
  77788. if (mesh && plugin) {
  77789. plugin.syncMeshWithImpostor(mesh, impostor);
  77790. }
  77791. }
  77792. }
  77793. };
  77794. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77795. if (!this._scene) {
  77796. return;
  77797. }
  77798. for (var i = 0; i < this._numMeshes; i++) {
  77799. if (this._impostors[i] == impostor) {
  77800. return;
  77801. }
  77802. }
  77803. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77804. if (debugMesh) {
  77805. this._impostors[this._numMeshes] = impostor;
  77806. this._meshes[this._numMeshes] = debugMesh;
  77807. if (this._numMeshes === 0) {
  77808. this._renderFunction = this._updateDebugMeshes.bind(this);
  77809. this._scene.registerBeforeRender(this._renderFunction);
  77810. }
  77811. this._numMeshes++;
  77812. }
  77813. };
  77814. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77815. if (!impostor || !this._scene) {
  77816. return;
  77817. }
  77818. var removed = false;
  77819. for (var i = 0; i < this._numMeshes; i++) {
  77820. if (this._impostors[i] == impostor) {
  77821. var mesh = this._meshes[i];
  77822. if (!mesh) {
  77823. continue;
  77824. }
  77825. this._scene.removeMesh(mesh);
  77826. mesh.dispose();
  77827. this._numMeshes--;
  77828. if (this._numMeshes > 0) {
  77829. this._meshes[i] = this._meshes[this._numMeshes];
  77830. this._impostors[i] = this._impostors[this._numMeshes];
  77831. this._meshes[this._numMeshes] = null;
  77832. this._impostors[this._numMeshes] = null;
  77833. }
  77834. else {
  77835. this._meshes[0] = null;
  77836. this._impostors[0] = null;
  77837. }
  77838. removed = true;
  77839. break;
  77840. }
  77841. }
  77842. if (removed && this._numMeshes === 0) {
  77843. this._scene.unregisterBeforeRender(this._renderFunction);
  77844. }
  77845. };
  77846. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77847. if (!this._debugMaterial) {
  77848. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77849. this._debugMaterial.wireframe = true;
  77850. }
  77851. return this._debugMaterial;
  77852. };
  77853. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77854. if (!this._debugBoxMesh) {
  77855. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77856. this._debugBoxMesh.renderingGroupId = 1;
  77857. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77858. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77859. scene.removeMesh(this._debugBoxMesh);
  77860. }
  77861. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77862. };
  77863. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77864. if (!this._debugSphereMesh) {
  77865. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77866. this._debugSphereMesh.renderingGroupId = 1;
  77867. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77868. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77869. scene.removeMesh(this._debugSphereMesh);
  77870. }
  77871. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77872. };
  77873. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77874. var mesh = null;
  77875. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77876. mesh = this._getDebugBoxMesh(scene);
  77877. impostor.getBoxSizeToRef(mesh.scaling);
  77878. }
  77879. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77880. mesh = this._getDebugSphereMesh(scene);
  77881. var radius = impostor.getRadius();
  77882. mesh.scaling.x = radius * 2;
  77883. mesh.scaling.y = radius * 2;
  77884. mesh.scaling.z = radius * 2;
  77885. }
  77886. return mesh;
  77887. };
  77888. PhysicsViewer.prototype.dispose = function () {
  77889. for (var i = 0; i < this._numMeshes; i++) {
  77890. this.hideImpostor(this._impostors[i]);
  77891. }
  77892. if (this._debugBoxMesh) {
  77893. this._debugBoxMesh.dispose();
  77894. }
  77895. if (this._debugSphereMesh) {
  77896. this._debugSphereMesh.dispose();
  77897. }
  77898. if (this._debugMaterial) {
  77899. this._debugMaterial.dispose();
  77900. }
  77901. this._impostors.length = 0;
  77902. this._scene = null;
  77903. this._physicsEnginePlugin = null;
  77904. };
  77905. return PhysicsViewer;
  77906. }());
  77907. Debug.SkeletonViewer = /** @class */ (function () {
  77908. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77909. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77910. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77911. this.skeleton = skeleton;
  77912. this.mesh = mesh;
  77913. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77914. this.renderingGroupId = renderingGroupId;
  77915. this.color = BABYLON.Color3.White();
  77916. this._debugLines = new Array();
  77917. this._isEnabled = false;
  77918. this._scene = scene;
  77919. this.update();
  77920. this._renderFunction = this.update.bind(this);
  77921. }
  77922. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77923. get: function () {
  77924. return this._isEnabled;
  77925. },
  77926. set: function (value) {
  77927. if (this._isEnabled === value) {
  77928. return;
  77929. }
  77930. this._isEnabled = value;
  77931. if (value) {
  77932. this._scene.registerBeforeRender(this._renderFunction);
  77933. }
  77934. else {
  77935. this._scene.unregisterBeforeRender(this._renderFunction);
  77936. }
  77937. },
  77938. enumerable: true,
  77939. configurable: true
  77940. });
  77941. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77942. if (x === void 0) { x = 0; }
  77943. if (y === void 0) { y = 0; }
  77944. if (z === void 0) { z = 0; }
  77945. var tmat = BABYLON.Tmp.Matrix[0];
  77946. var parentBone = bone.getParent();
  77947. tmat.copyFrom(bone.getLocalMatrix());
  77948. if (x !== 0 || y !== 0 || z !== 0) {
  77949. var tmat2 = BABYLON.Tmp.Matrix[1];
  77950. BABYLON.Matrix.IdentityToRef(tmat2);
  77951. tmat2.m[12] = x;
  77952. tmat2.m[13] = y;
  77953. tmat2.m[14] = z;
  77954. tmat2.multiplyToRef(tmat, tmat);
  77955. }
  77956. if (parentBone) {
  77957. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77958. }
  77959. tmat.multiplyToRef(meshMat, tmat);
  77960. position.x = tmat.m[12];
  77961. position.y = tmat.m[13];
  77962. position.z = tmat.m[14];
  77963. };
  77964. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77965. var len = bones.length;
  77966. var meshPos = this.mesh.position;
  77967. for (var i = 0; i < len; i++) {
  77968. var bone = bones[i];
  77969. var points = this._debugLines[i];
  77970. if (!points) {
  77971. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77972. this._debugLines[i] = points;
  77973. }
  77974. this._getBonePosition(points[0], bone, meshMat);
  77975. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77976. points[0].subtractInPlace(meshPos);
  77977. points[1].subtractInPlace(meshPos);
  77978. }
  77979. };
  77980. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77981. var len = bones.length;
  77982. var boneNum = 0;
  77983. var meshPos = this.mesh.position;
  77984. for (var i = len - 1; i >= 0; i--) {
  77985. var childBone = bones[i];
  77986. var parentBone = childBone.getParent();
  77987. if (!parentBone) {
  77988. continue;
  77989. }
  77990. var points = this._debugLines[boneNum];
  77991. if (!points) {
  77992. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77993. this._debugLines[boneNum] = points;
  77994. }
  77995. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77996. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77997. points[0].subtractInPlace(meshPos);
  77998. points[1].subtractInPlace(meshPos);
  77999. boneNum++;
  78000. }
  78001. };
  78002. SkeletonViewer.prototype.update = function () {
  78003. if (this.autoUpdateBonesMatrices) {
  78004. this.skeleton.computeAbsoluteTransforms();
  78005. }
  78006. if (this.skeleton.bones[0].length === undefined) {
  78007. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78008. }
  78009. else {
  78010. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78011. }
  78012. if (!this._debugMesh) {
  78013. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78014. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78015. }
  78016. else {
  78017. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78018. }
  78019. this._debugMesh.position.copyFrom(this.mesh.position);
  78020. this._debugMesh.color = this.color;
  78021. };
  78022. SkeletonViewer.prototype.dispose = function () {
  78023. if (this._debugMesh) {
  78024. this.isEnabled = false;
  78025. this._debugMesh.dispose();
  78026. this._debugMesh = null;
  78027. }
  78028. };
  78029. return SkeletonViewer;
  78030. }());
  78031. return Debug;
  78032. }());
  78033. BABYLON.Debug = Debug;
  78034. })(BABYLON || (BABYLON = {}));
  78035. //# sourceMappingURL=babylon.debugModules.js.map
  78036. var BABYLON;
  78037. (function (BABYLON) {
  78038. var RayHelper = /** @class */ (function () {
  78039. function RayHelper(ray) {
  78040. this.ray = ray;
  78041. }
  78042. RayHelper.CreateAndShow = function (ray, scene, color) {
  78043. var helper = new RayHelper(ray);
  78044. helper.show(scene, color);
  78045. return helper;
  78046. };
  78047. RayHelper.prototype.show = function (scene, color) {
  78048. if (!this._renderFunction && this.ray) {
  78049. var ray = this.ray;
  78050. this._renderFunction = this._render.bind(this);
  78051. this._scene = scene;
  78052. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78053. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78054. if (this._renderFunction) {
  78055. this._scene.registerBeforeRender(this._renderFunction);
  78056. }
  78057. }
  78058. if (color && this._renderLine) {
  78059. this._renderLine.color.copyFrom(color);
  78060. }
  78061. };
  78062. RayHelper.prototype.hide = function () {
  78063. if (this._renderFunction && this._scene) {
  78064. this._scene.unregisterBeforeRender(this._renderFunction);
  78065. this._scene = null;
  78066. this._renderFunction = null;
  78067. if (this._renderLine) {
  78068. this._renderLine.dispose();
  78069. this._renderLine = null;
  78070. }
  78071. this._renderPoints = [];
  78072. }
  78073. };
  78074. RayHelper.prototype._render = function () {
  78075. var ray = this.ray;
  78076. if (!ray) {
  78077. return;
  78078. }
  78079. var point = this._renderPoints[1];
  78080. var len = Math.min(ray.length, 1000000);
  78081. point.copyFrom(ray.direction);
  78082. point.scaleInPlace(len);
  78083. point.addInPlace(ray.origin);
  78084. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78085. };
  78086. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78087. this._attachedToMesh = mesh;
  78088. var ray = this.ray;
  78089. if (!ray) {
  78090. return;
  78091. }
  78092. if (!ray.direction) {
  78093. ray.direction = BABYLON.Vector3.Zero();
  78094. }
  78095. if (!ray.origin) {
  78096. ray.origin = BABYLON.Vector3.Zero();
  78097. }
  78098. if (length) {
  78099. ray.length = length;
  78100. }
  78101. if (!meshSpaceOrigin) {
  78102. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78103. }
  78104. if (!meshSpaceDirection) {
  78105. // -1 so that this will work with Mesh.lookAt
  78106. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78107. }
  78108. if (!this._meshSpaceDirection) {
  78109. this._meshSpaceDirection = meshSpaceDirection.clone();
  78110. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78111. }
  78112. else {
  78113. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78114. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78115. }
  78116. if (!this._updateToMeshFunction) {
  78117. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78118. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78119. }
  78120. this._updateToMesh();
  78121. };
  78122. RayHelper.prototype.detachFromMesh = function () {
  78123. if (this._attachedToMesh) {
  78124. if (this._updateToMeshFunction) {
  78125. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78126. }
  78127. this._attachedToMesh = null;
  78128. this._updateToMeshFunction = null;
  78129. }
  78130. };
  78131. RayHelper.prototype._updateToMesh = function () {
  78132. var ray = this.ray;
  78133. if (!this._attachedToMesh || !ray) {
  78134. return;
  78135. }
  78136. if (this._attachedToMesh._isDisposed) {
  78137. this.detachFromMesh();
  78138. return;
  78139. }
  78140. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78141. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78142. };
  78143. RayHelper.prototype.dispose = function () {
  78144. this.hide();
  78145. this.detachFromMesh();
  78146. this.ray = null;
  78147. };
  78148. return RayHelper;
  78149. }());
  78150. BABYLON.RayHelper = RayHelper;
  78151. })(BABYLON || (BABYLON = {}));
  78152. //# sourceMappingURL=babylon.rayHelper.js.map
  78153. var BABYLON;
  78154. (function (BABYLON) {
  78155. // load the inspector using require, if not present in the global namespace.
  78156. var DebugLayer = /** @class */ (function () {
  78157. function DebugLayer(scene) {
  78158. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78159. this._scene = scene;
  78160. // load inspector using require, if it doesn't exist on the global namespace.
  78161. }
  78162. /** Creates the inspector window. */
  78163. DebugLayer.prototype._createInspector = function (config) {
  78164. if (config === void 0) { config = {}; }
  78165. var popup = config.popup || false;
  78166. var initialTab = config.initialTab || 0;
  78167. var parentElement = config.parentElement || null;
  78168. if (!this._inspector) {
  78169. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78170. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78171. } // else nothing to do,; instance is already existing
  78172. };
  78173. DebugLayer.prototype.isVisible = function () {
  78174. if (!this._inspector) {
  78175. return false;
  78176. }
  78177. return true;
  78178. };
  78179. DebugLayer.prototype.hide = function () {
  78180. if (this._inspector) {
  78181. try {
  78182. this._inspector.dispose();
  78183. }
  78184. catch (e) {
  78185. // If the inspector has been removed directly from the inspector tool
  78186. }
  78187. this._inspector = null;
  78188. }
  78189. };
  78190. DebugLayer.prototype.show = function (config) {
  78191. if (config === void 0) { config = {}; }
  78192. if (typeof this.BJSINSPECTOR == 'undefined') {
  78193. // Load inspector and add it to the DOM
  78194. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78195. }
  78196. else {
  78197. // Otherwise creates the inspector
  78198. this._createInspector(config);
  78199. }
  78200. };
  78201. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78202. return DebugLayer;
  78203. }());
  78204. BABYLON.DebugLayer = DebugLayer;
  78205. })(BABYLON || (BABYLON = {}));
  78206. //# sourceMappingURL=babylon.debugLayer.js.map
  78207. var BABYLON;
  78208. (function (BABYLON) {
  78209. var BoundingBoxRenderer = /** @class */ (function () {
  78210. function BoundingBoxRenderer(scene) {
  78211. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78212. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78213. this.showBackLines = true;
  78214. this.renderList = new BABYLON.SmartArray(32);
  78215. this._vertexBuffers = {};
  78216. this._scene = scene;
  78217. }
  78218. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78219. if (this._colorShader) {
  78220. return;
  78221. }
  78222. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78223. attributes: [BABYLON.VertexBuffer.PositionKind],
  78224. uniforms: ["world", "viewProjection", "color"]
  78225. });
  78226. var engine = this._scene.getEngine();
  78227. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78228. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78229. this._createIndexBuffer();
  78230. };
  78231. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78232. var engine = this._scene.getEngine();
  78233. 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]);
  78234. };
  78235. BoundingBoxRenderer.prototype._rebuild = function () {
  78236. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78237. if (vb) {
  78238. vb._rebuild();
  78239. }
  78240. this._createIndexBuffer();
  78241. };
  78242. BoundingBoxRenderer.prototype.reset = function () {
  78243. this.renderList.reset();
  78244. };
  78245. BoundingBoxRenderer.prototype.render = function () {
  78246. if (this.renderList.length === 0) {
  78247. return;
  78248. }
  78249. this._prepareRessources();
  78250. if (!this._colorShader.isReady()) {
  78251. return;
  78252. }
  78253. var engine = this._scene.getEngine();
  78254. engine.setDepthWrite(false);
  78255. this._colorShader._preBind();
  78256. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78257. var boundingBox = this.renderList.data[boundingBoxIndex];
  78258. var min = boundingBox.minimum;
  78259. var max = boundingBox.maximum;
  78260. var diff = max.subtract(min);
  78261. var median = min.add(diff.scale(0.5));
  78262. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78263. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78264. .multiply(boundingBox.getWorldMatrix());
  78265. // VBOs
  78266. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78267. if (this.showBackLines) {
  78268. // Back
  78269. engine.setDepthFunctionToGreaterOrEqual();
  78270. this._scene.resetCachedMaterial();
  78271. this._colorShader.setColor4("color", this.backColor.toColor4());
  78272. this._colorShader.bind(worldMatrix);
  78273. // Draw order
  78274. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78275. }
  78276. // Front
  78277. engine.setDepthFunctionToLess();
  78278. this._scene.resetCachedMaterial();
  78279. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78280. this._colorShader.bind(worldMatrix);
  78281. // Draw order
  78282. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78283. }
  78284. this._colorShader.unbind();
  78285. engine.setDepthFunctionToLessOrEqual();
  78286. engine.setDepthWrite(true);
  78287. };
  78288. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78289. this._prepareRessources();
  78290. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78291. return;
  78292. }
  78293. var engine = this._scene.getEngine();
  78294. engine.setDepthWrite(false);
  78295. engine.setColorWrite(false);
  78296. this._colorShader._preBind();
  78297. var boundingBox = mesh._boundingInfo.boundingBox;
  78298. var min = boundingBox.minimum;
  78299. var max = boundingBox.maximum;
  78300. var diff = max.subtract(min);
  78301. var median = min.add(diff.scale(0.5));
  78302. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78303. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78304. .multiply(boundingBox.getWorldMatrix());
  78305. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78306. engine.setDepthFunctionToLess();
  78307. this._scene.resetCachedMaterial();
  78308. this._colorShader.bind(worldMatrix);
  78309. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78310. this._colorShader.unbind();
  78311. engine.setDepthFunctionToLessOrEqual();
  78312. engine.setDepthWrite(true);
  78313. engine.setColorWrite(true);
  78314. };
  78315. BoundingBoxRenderer.prototype.dispose = function () {
  78316. if (!this._colorShader) {
  78317. return;
  78318. }
  78319. this.renderList.dispose();
  78320. this._colorShader.dispose();
  78321. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78322. if (buffer) {
  78323. buffer.dispose();
  78324. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78325. }
  78326. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78327. };
  78328. return BoundingBoxRenderer;
  78329. }());
  78330. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78331. })(BABYLON || (BABYLON = {}));
  78332. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78333. var BABYLON;
  78334. (function (BABYLON) {
  78335. var MorphTarget = /** @class */ (function () {
  78336. function MorphTarget(name, influence) {
  78337. if (influence === void 0) { influence = 0; }
  78338. this.name = name;
  78339. this.animations = new Array();
  78340. this._positions = null;
  78341. this._normals = null;
  78342. this._tangents = null;
  78343. this.onInfluenceChanged = new BABYLON.Observable();
  78344. this.influence = influence;
  78345. }
  78346. Object.defineProperty(MorphTarget.prototype, "influence", {
  78347. get: function () {
  78348. return this._influence;
  78349. },
  78350. set: function (influence) {
  78351. if (this._influence === influence) {
  78352. return;
  78353. }
  78354. var previous = this._influence;
  78355. this._influence = influence;
  78356. if (this.onInfluenceChanged.hasObservers) {
  78357. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78358. }
  78359. },
  78360. enumerable: true,
  78361. configurable: true
  78362. });
  78363. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78364. get: function () {
  78365. return !!this._positions;
  78366. },
  78367. enumerable: true,
  78368. configurable: true
  78369. });
  78370. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78371. get: function () {
  78372. return !!this._normals;
  78373. },
  78374. enumerable: true,
  78375. configurable: true
  78376. });
  78377. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78378. get: function () {
  78379. return !!this._tangents;
  78380. },
  78381. enumerable: true,
  78382. configurable: true
  78383. });
  78384. MorphTarget.prototype.setPositions = function (data) {
  78385. this._positions = data;
  78386. };
  78387. MorphTarget.prototype.getPositions = function () {
  78388. return this._positions;
  78389. };
  78390. MorphTarget.prototype.setNormals = function (data) {
  78391. this._normals = data;
  78392. };
  78393. MorphTarget.prototype.getNormals = function () {
  78394. return this._normals;
  78395. };
  78396. MorphTarget.prototype.setTangents = function (data) {
  78397. this._tangents = data;
  78398. };
  78399. MorphTarget.prototype.getTangents = function () {
  78400. return this._tangents;
  78401. };
  78402. /**
  78403. * Serializes the current target into a Serialization object.
  78404. * Returns the serialized object.
  78405. */
  78406. MorphTarget.prototype.serialize = function () {
  78407. var serializationObject = {};
  78408. serializationObject.name = this.name;
  78409. serializationObject.influence = this.influence;
  78410. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78411. if (this.hasNormals) {
  78412. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78413. }
  78414. if (this.hasTangents) {
  78415. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78416. }
  78417. // Animations
  78418. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78419. return serializationObject;
  78420. };
  78421. // Statics
  78422. MorphTarget.Parse = function (serializationObject) {
  78423. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78424. result.setPositions(serializationObject.positions);
  78425. if (serializationObject.normals) {
  78426. result.setNormals(serializationObject.normals);
  78427. }
  78428. if (serializationObject.tangents) {
  78429. result.setTangents(serializationObject.tangents);
  78430. }
  78431. // Animations
  78432. if (serializationObject.animations) {
  78433. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78434. var parsedAnimation = serializationObject.animations[animationIndex];
  78435. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78436. }
  78437. }
  78438. return result;
  78439. };
  78440. MorphTarget.FromMesh = function (mesh, name, influence) {
  78441. if (!name) {
  78442. name = mesh.name;
  78443. }
  78444. var result = new MorphTarget(name, influence);
  78445. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78446. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78447. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78448. }
  78449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78450. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78451. }
  78452. return result;
  78453. };
  78454. return MorphTarget;
  78455. }());
  78456. BABYLON.MorphTarget = MorphTarget;
  78457. })(BABYLON || (BABYLON = {}));
  78458. //# sourceMappingURL=babylon.morphTarget.js.map
  78459. var BABYLON;
  78460. (function (BABYLON) {
  78461. var MorphTargetManager = /** @class */ (function () {
  78462. function MorphTargetManager(scene) {
  78463. if (scene === void 0) { scene = null; }
  78464. this._targets = new Array();
  78465. this._targetObservable = new Array();
  78466. this._activeTargets = new BABYLON.SmartArray(16);
  78467. this._supportsNormals = false;
  78468. this._supportsTangents = false;
  78469. this._vertexCount = 0;
  78470. this._uniqueId = 0;
  78471. this._tempInfluences = new Array();
  78472. if (!scene) {
  78473. scene = BABYLON.Engine.LastCreatedScene;
  78474. }
  78475. this._scene = scene;
  78476. if (this._scene) {
  78477. this._scene.morphTargetManagers.push(this);
  78478. this._uniqueId = this._scene.getUniqueId();
  78479. }
  78480. }
  78481. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78482. get: function () {
  78483. return this._uniqueId;
  78484. },
  78485. enumerable: true,
  78486. configurable: true
  78487. });
  78488. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78489. get: function () {
  78490. return this._vertexCount;
  78491. },
  78492. enumerable: true,
  78493. configurable: true
  78494. });
  78495. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78496. get: function () {
  78497. return this._supportsNormals;
  78498. },
  78499. enumerable: true,
  78500. configurable: true
  78501. });
  78502. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78503. get: function () {
  78504. return this._supportsTangents;
  78505. },
  78506. enumerable: true,
  78507. configurable: true
  78508. });
  78509. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78510. get: function () {
  78511. return this._targets.length;
  78512. },
  78513. enumerable: true,
  78514. configurable: true
  78515. });
  78516. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78517. get: function () {
  78518. return this._activeTargets.length;
  78519. },
  78520. enumerable: true,
  78521. configurable: true
  78522. });
  78523. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78524. get: function () {
  78525. return this._influences;
  78526. },
  78527. enumerable: true,
  78528. configurable: true
  78529. });
  78530. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78531. return this._activeTargets.data[index];
  78532. };
  78533. MorphTargetManager.prototype.getTarget = function (index) {
  78534. return this._targets[index];
  78535. };
  78536. MorphTargetManager.prototype.addTarget = function (target) {
  78537. var _this = this;
  78538. this._targets.push(target);
  78539. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78540. _this._syncActiveTargets(needUpdate);
  78541. }));
  78542. this._syncActiveTargets(true);
  78543. };
  78544. MorphTargetManager.prototype.removeTarget = function (target) {
  78545. var index = this._targets.indexOf(target);
  78546. if (index >= 0) {
  78547. this._targets.splice(index, 1);
  78548. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78549. this._syncActiveTargets(true);
  78550. }
  78551. };
  78552. /**
  78553. * Serializes the current manager into a Serialization object.
  78554. * Returns the serialized object.
  78555. */
  78556. MorphTargetManager.prototype.serialize = function () {
  78557. var serializationObject = {};
  78558. serializationObject.id = this.uniqueId;
  78559. serializationObject.targets = [];
  78560. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78561. var target = _a[_i];
  78562. serializationObject.targets.push(target.serialize());
  78563. }
  78564. return serializationObject;
  78565. };
  78566. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78567. var influenceCount = 0;
  78568. this._activeTargets.reset();
  78569. this._supportsNormals = true;
  78570. this._supportsTangents = true;
  78571. this._vertexCount = 0;
  78572. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78573. var target = _a[_i];
  78574. this._activeTargets.push(target);
  78575. this._tempInfluences[influenceCount++] = target.influence;
  78576. var positions = target.getPositions();
  78577. if (positions) {
  78578. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78579. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78580. var vertexCount = positions.length / 3;
  78581. if (this._vertexCount === 0) {
  78582. this._vertexCount = vertexCount;
  78583. }
  78584. else if (this._vertexCount !== vertexCount) {
  78585. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78586. return;
  78587. }
  78588. }
  78589. }
  78590. if (!this._influences || this._influences.length !== influenceCount) {
  78591. this._influences = new Float32Array(influenceCount);
  78592. }
  78593. for (var index = 0; index < influenceCount; index++) {
  78594. this._influences[index] = this._tempInfluences[index];
  78595. }
  78596. if (needUpdate && this._scene) {
  78597. // Flag meshes as dirty to resync with the active targets
  78598. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78599. var mesh = _c[_b];
  78600. if (mesh.morphTargetManager === this) {
  78601. mesh._syncGeometryWithMorphTargetManager();
  78602. }
  78603. }
  78604. }
  78605. };
  78606. // Statics
  78607. MorphTargetManager.Parse = function (serializationObject, scene) {
  78608. var result = new MorphTargetManager(scene);
  78609. result._uniqueId = serializationObject.id;
  78610. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78611. var targetData = _a[_i];
  78612. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78613. }
  78614. return result;
  78615. };
  78616. return MorphTargetManager;
  78617. }());
  78618. BABYLON.MorphTargetManager = MorphTargetManager;
  78619. })(BABYLON || (BABYLON = {}));
  78620. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78621. var BABYLON;
  78622. (function (BABYLON) {
  78623. var Octree = /** @class */ (function () {
  78624. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78625. if (maxDepth === void 0) { maxDepth = 2; }
  78626. this.maxDepth = maxDepth;
  78627. this.dynamicContent = new Array();
  78628. this._maxBlockCapacity = maxBlockCapacity || 64;
  78629. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78630. this._creationFunc = creationFunc;
  78631. }
  78632. // Methods
  78633. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78634. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78635. };
  78636. Octree.prototype.addMesh = function (entry) {
  78637. for (var index = 0; index < this.blocks.length; index++) {
  78638. var block = this.blocks[index];
  78639. block.addEntry(entry);
  78640. }
  78641. };
  78642. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78643. this._selectionContent.reset();
  78644. for (var index = 0; index < this.blocks.length; index++) {
  78645. var block = this.blocks[index];
  78646. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78647. }
  78648. if (allowDuplicate) {
  78649. this._selectionContent.concat(this.dynamicContent);
  78650. }
  78651. else {
  78652. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78653. }
  78654. return this._selectionContent;
  78655. };
  78656. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78657. this._selectionContent.reset();
  78658. for (var index = 0; index < this.blocks.length; index++) {
  78659. var block = this.blocks[index];
  78660. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78661. }
  78662. if (allowDuplicate) {
  78663. this._selectionContent.concat(this.dynamicContent);
  78664. }
  78665. else {
  78666. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78667. }
  78668. return this._selectionContent;
  78669. };
  78670. Octree.prototype.intersectsRay = function (ray) {
  78671. this._selectionContent.reset();
  78672. for (var index = 0; index < this.blocks.length; index++) {
  78673. var block = this.blocks[index];
  78674. block.intersectsRay(ray, this._selectionContent);
  78675. }
  78676. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78677. return this._selectionContent;
  78678. };
  78679. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78680. target.blocks = new Array();
  78681. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78682. // Segmenting space
  78683. for (var x = 0; x < 2; x++) {
  78684. for (var y = 0; y < 2; y++) {
  78685. for (var z = 0; z < 2; z++) {
  78686. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78687. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78688. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78689. block.addEntries(entries);
  78690. target.blocks.push(block);
  78691. }
  78692. }
  78693. }
  78694. };
  78695. Octree.CreationFuncForMeshes = function (entry, block) {
  78696. var boundingInfo = entry.getBoundingInfo();
  78697. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78698. block.entries.push(entry);
  78699. }
  78700. };
  78701. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78702. var boundingInfo = entry.getBoundingInfo();
  78703. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78704. block.entries.push(entry);
  78705. }
  78706. };
  78707. return Octree;
  78708. }());
  78709. BABYLON.Octree = Octree;
  78710. })(BABYLON || (BABYLON = {}));
  78711. //# sourceMappingURL=babylon.octree.js.map
  78712. var BABYLON;
  78713. (function (BABYLON) {
  78714. var OctreeBlock = /** @class */ (function () {
  78715. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78716. this.entries = new Array();
  78717. this._boundingVectors = new Array();
  78718. this._capacity = capacity;
  78719. this._depth = depth;
  78720. this._maxDepth = maxDepth;
  78721. this._creationFunc = creationFunc;
  78722. this._minPoint = minPoint;
  78723. this._maxPoint = maxPoint;
  78724. this._boundingVectors.push(minPoint.clone());
  78725. this._boundingVectors.push(maxPoint.clone());
  78726. this._boundingVectors.push(minPoint.clone());
  78727. this._boundingVectors[2].x = maxPoint.x;
  78728. this._boundingVectors.push(minPoint.clone());
  78729. this._boundingVectors[3].y = maxPoint.y;
  78730. this._boundingVectors.push(minPoint.clone());
  78731. this._boundingVectors[4].z = maxPoint.z;
  78732. this._boundingVectors.push(maxPoint.clone());
  78733. this._boundingVectors[5].z = minPoint.z;
  78734. this._boundingVectors.push(maxPoint.clone());
  78735. this._boundingVectors[6].x = minPoint.x;
  78736. this._boundingVectors.push(maxPoint.clone());
  78737. this._boundingVectors[7].y = minPoint.y;
  78738. }
  78739. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78740. // Property
  78741. get: function () {
  78742. return this._capacity;
  78743. },
  78744. enumerable: true,
  78745. configurable: true
  78746. });
  78747. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78748. get: function () {
  78749. return this._minPoint;
  78750. },
  78751. enumerable: true,
  78752. configurable: true
  78753. });
  78754. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78755. get: function () {
  78756. return this._maxPoint;
  78757. },
  78758. enumerable: true,
  78759. configurable: true
  78760. });
  78761. // Methods
  78762. OctreeBlock.prototype.addEntry = function (entry) {
  78763. if (this.blocks) {
  78764. for (var index = 0; index < this.blocks.length; index++) {
  78765. var block = this.blocks[index];
  78766. block.addEntry(entry);
  78767. }
  78768. return;
  78769. }
  78770. this._creationFunc(entry, this);
  78771. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78772. this.createInnerBlocks();
  78773. }
  78774. };
  78775. OctreeBlock.prototype.addEntries = function (entries) {
  78776. for (var index = 0; index < entries.length; index++) {
  78777. var mesh = entries[index];
  78778. this.addEntry(mesh);
  78779. }
  78780. };
  78781. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78782. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78783. if (this.blocks) {
  78784. for (var index = 0; index < this.blocks.length; index++) {
  78785. var block = this.blocks[index];
  78786. block.select(frustumPlanes, selection, allowDuplicate);
  78787. }
  78788. return;
  78789. }
  78790. if (allowDuplicate) {
  78791. selection.concat(this.entries);
  78792. }
  78793. else {
  78794. selection.concatWithNoDuplicate(this.entries);
  78795. }
  78796. }
  78797. };
  78798. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78799. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78800. if (this.blocks) {
  78801. for (var index = 0; index < this.blocks.length; index++) {
  78802. var block = this.blocks[index];
  78803. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78804. }
  78805. return;
  78806. }
  78807. if (allowDuplicate) {
  78808. selection.concat(this.entries);
  78809. }
  78810. else {
  78811. selection.concatWithNoDuplicate(this.entries);
  78812. }
  78813. }
  78814. };
  78815. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78816. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78817. if (this.blocks) {
  78818. for (var index = 0; index < this.blocks.length; index++) {
  78819. var block = this.blocks[index];
  78820. block.intersectsRay(ray, selection);
  78821. }
  78822. return;
  78823. }
  78824. selection.concatWithNoDuplicate(this.entries);
  78825. }
  78826. };
  78827. OctreeBlock.prototype.createInnerBlocks = function () {
  78828. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78829. };
  78830. return OctreeBlock;
  78831. }());
  78832. BABYLON.OctreeBlock = OctreeBlock;
  78833. })(BABYLON || (BABYLON = {}));
  78834. //# sourceMappingURL=babylon.octreeBlock.js.map
  78835. var BABYLON;
  78836. (function (BABYLON) {
  78837. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78838. __extends(VRDistortionCorrectionPostProcess, _super);
  78839. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78840. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78841. 'LensCenter',
  78842. 'Scale',
  78843. 'ScaleIn',
  78844. 'HmdWarpParam'
  78845. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78846. _this._isRightEye = isRightEye;
  78847. _this._distortionFactors = vrMetrics.distortionK;
  78848. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78849. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78850. _this.adaptScaleToCurrentViewport = true;
  78851. _this.onSizeChangedObservable.add(function () {
  78852. _this.aspectRatio = _this.width * .5 / _this.height;
  78853. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78854. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78855. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78856. });
  78857. _this.onApplyObservable.add(function (effect) {
  78858. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78859. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78860. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78861. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78862. });
  78863. return _this;
  78864. }
  78865. return VRDistortionCorrectionPostProcess;
  78866. }(BABYLON.PostProcess));
  78867. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78868. })(BABYLON || (BABYLON = {}));
  78869. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78870. var BABYLON;
  78871. (function (BABYLON) {
  78872. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78873. __extends(AnaglyphPostProcess, _super);
  78874. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78875. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78876. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78877. _this.onApplyObservable.add(function (effect) {
  78878. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78879. });
  78880. return _this;
  78881. }
  78882. return AnaglyphPostProcess;
  78883. }(BABYLON.PostProcess));
  78884. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78885. })(BABYLON || (BABYLON = {}));
  78886. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78887. var BABYLON;
  78888. (function (BABYLON) {
  78889. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78890. __extends(StereoscopicInterlacePostProcess, _super);
  78891. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78892. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78893. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78894. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78895. _this.onSizeChangedObservable.add(function () {
  78896. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78897. });
  78898. _this.onApplyObservable.add(function (effect) {
  78899. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78900. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78901. });
  78902. return _this;
  78903. }
  78904. return StereoscopicInterlacePostProcess;
  78905. }(BABYLON.PostProcess));
  78906. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78907. })(BABYLON || (BABYLON = {}));
  78908. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78909. var BABYLON;
  78910. (function (BABYLON) {
  78911. /**
  78912. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78913. * Screen rotation is taken into account.
  78914. */
  78915. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78916. function FreeCameraDeviceOrientationInput() {
  78917. var _this = this;
  78918. this._screenOrientationAngle = 0;
  78919. this._screenQuaternion = new BABYLON.Quaternion();
  78920. this._alpha = 0;
  78921. this._beta = 0;
  78922. this._gamma = 0;
  78923. this._orientationChanged = function () {
  78924. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78925. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78926. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78927. };
  78928. this._deviceOrientation = function (evt) {
  78929. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78930. _this._beta = evt.beta !== null ? evt.beta : 0;
  78931. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78932. };
  78933. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78934. this._orientationChanged();
  78935. }
  78936. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78937. get: function () {
  78938. return this._camera;
  78939. },
  78940. set: function (camera) {
  78941. this._camera = camera;
  78942. if (this._camera != null && !this._camera.rotationQuaternion) {
  78943. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78944. }
  78945. },
  78946. enumerable: true,
  78947. configurable: true
  78948. });
  78949. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78950. window.addEventListener("orientationchange", this._orientationChanged);
  78951. window.addEventListener("deviceorientation", this._deviceOrientation);
  78952. //In certain cases, the attach control is called AFTER orientation was changed,
  78953. //So this is needed.
  78954. this._orientationChanged();
  78955. };
  78956. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78957. window.removeEventListener("orientationchange", this._orientationChanged);
  78958. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78959. };
  78960. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78961. //if no device orientation provided, don't update the rotation.
  78962. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78963. if (!this._alpha)
  78964. return;
  78965. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78966. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78967. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78968. //Mirror on XY Plane
  78969. this._camera.rotationQuaternion.z *= -1;
  78970. this._camera.rotationQuaternion.w *= -1;
  78971. };
  78972. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78973. return "FreeCameraDeviceOrientationInput";
  78974. };
  78975. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78976. return "deviceOrientation";
  78977. };
  78978. return FreeCameraDeviceOrientationInput;
  78979. }());
  78980. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78981. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78982. })(BABYLON || (BABYLON = {}));
  78983. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78984. var BABYLON;
  78985. (function (BABYLON) {
  78986. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78987. function ArcRotateCameraVRDeviceOrientationInput() {
  78988. this.alphaCorrection = 1;
  78989. this.betaCorrection = 1;
  78990. this.gammaCorrection = 1;
  78991. this._alpha = 0;
  78992. this._gamma = 0;
  78993. this._dirty = false;
  78994. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78995. }
  78996. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78997. this.camera.attachControl(element, noPreventDefault);
  78998. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78999. };
  79000. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79001. if (evt.alpha !== null) {
  79002. this._alpha = +evt.alpha | 0;
  79003. }
  79004. if (evt.gamma !== null) {
  79005. this._gamma = +evt.gamma | 0;
  79006. }
  79007. this._dirty = true;
  79008. };
  79009. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79010. if (this._dirty) {
  79011. this._dirty = false;
  79012. if (this._gamma < 0) {
  79013. this._gamma = 180 + this._gamma;
  79014. }
  79015. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79016. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79017. }
  79018. };
  79019. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79020. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79021. };
  79022. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79023. return "ArcRotateCameraVRDeviceOrientationInput";
  79024. };
  79025. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79026. return "VRDeviceOrientation";
  79027. };
  79028. return ArcRotateCameraVRDeviceOrientationInput;
  79029. }());
  79030. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79031. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79032. })(BABYLON || (BABYLON = {}));
  79033. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79034. var BABYLON;
  79035. (function (BABYLON) {
  79036. var VRCameraMetrics = /** @class */ (function () {
  79037. function VRCameraMetrics() {
  79038. this.compensateDistortion = true;
  79039. }
  79040. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79041. get: function () {
  79042. return this.hResolution / (2 * this.vResolution);
  79043. },
  79044. enumerable: true,
  79045. configurable: true
  79046. });
  79047. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79048. get: function () {
  79049. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79050. },
  79051. enumerable: true,
  79052. configurable: true
  79053. });
  79054. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79055. get: function () {
  79056. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79057. var h = (4 * meters) / this.hScreenSize;
  79058. return BABYLON.Matrix.Translation(h, 0, 0);
  79059. },
  79060. enumerable: true,
  79061. configurable: true
  79062. });
  79063. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79064. get: function () {
  79065. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79066. var h = (4 * meters) / this.hScreenSize;
  79067. return BABYLON.Matrix.Translation(-h, 0, 0);
  79068. },
  79069. enumerable: true,
  79070. configurable: true
  79071. });
  79072. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79073. get: function () {
  79074. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79080. get: function () {
  79081. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79082. },
  79083. enumerable: true,
  79084. configurable: true
  79085. });
  79086. VRCameraMetrics.GetDefault = function () {
  79087. var result = new VRCameraMetrics();
  79088. result.hResolution = 1280;
  79089. result.vResolution = 800;
  79090. result.hScreenSize = 0.149759993;
  79091. result.vScreenSize = 0.0935999975;
  79092. result.vScreenCenter = 0.0467999987;
  79093. result.eyeToScreenDistance = 0.0410000011;
  79094. result.lensSeparationDistance = 0.0635000020;
  79095. result.interpupillaryDistance = 0.0640000030;
  79096. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79097. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79098. result.postProcessScaleFactor = 1.714605507808412;
  79099. result.lensCenterOffset = 0.151976421;
  79100. return result;
  79101. };
  79102. return VRCameraMetrics;
  79103. }());
  79104. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79105. })(BABYLON || (BABYLON = {}));
  79106. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79107. var BABYLON;
  79108. (function (BABYLON) {
  79109. /**
  79110. * This represents a WebVR camera.
  79111. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79112. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79113. */
  79114. var WebVRFreeCamera = /** @class */ (function (_super) {
  79115. __extends(WebVRFreeCamera, _super);
  79116. /**
  79117. * Instantiates a WebVRFreeCamera.
  79118. * @param name The name of the WebVRFreeCamera
  79119. * @param position The starting anchor position for the camera
  79120. * @param scene The scene the camera belongs to
  79121. * @param webVROptions a set of customizable options for the webVRCamera
  79122. */
  79123. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79124. if (webVROptions === void 0) { webVROptions = {}; }
  79125. var _this = _super.call(this, name, position, scene) || this;
  79126. _this.webVROptions = webVROptions;
  79127. /**
  79128. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79129. */
  79130. _this._vrDevice = null;
  79131. /**
  79132. * The rawPose of the vrDevice.
  79133. */
  79134. _this.rawPose = null;
  79135. _this._specsVersion = "1.1";
  79136. _this._attached = false;
  79137. _this._descendants = [];
  79138. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79139. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79140. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79141. _this._standingMatrix = null;
  79142. /**
  79143. * Represents device position in babylon space.
  79144. */
  79145. _this.devicePosition = BABYLON.Vector3.Zero();
  79146. /**
  79147. * Represents device rotation in babylon space.
  79148. */
  79149. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79150. /**
  79151. * The scale of the device to be used when translating from device space to babylon space.
  79152. */
  79153. _this.deviceScaleFactor = 1;
  79154. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79155. _this._worldToDevice = BABYLON.Matrix.Identity();
  79156. /**
  79157. * References to the webVR controllers for the vrDevice.
  79158. */
  79159. _this.controllers = [];
  79160. /**
  79161. * Emits an event when a controller is attached.
  79162. */
  79163. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79164. /**
  79165. * Emits an event when a controller's mesh has been loaded;
  79166. */
  79167. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79168. /**
  79169. * If the rig cameras be used as parent instead of this camera.
  79170. */
  79171. _this.rigParenting = true;
  79172. _this._defaultHeight = undefined;
  79173. _this._workingVector = BABYLON.Vector3.Zero();
  79174. _this._oneVector = BABYLON.Vector3.One();
  79175. _this._workingMatrix = BABYLON.Matrix.Identity();
  79176. _this._cache.position = BABYLON.Vector3.Zero();
  79177. if (webVROptions.defaultHeight) {
  79178. _this._defaultHeight = webVROptions.defaultHeight;
  79179. _this.position.y = _this._defaultHeight;
  79180. }
  79181. _this.minZ = 0.1;
  79182. //legacy support - the compensation boolean was removed.
  79183. if (arguments.length === 5) {
  79184. _this.webVROptions = arguments[4];
  79185. }
  79186. // default webVR options
  79187. if (_this.webVROptions.trackPosition == undefined) {
  79188. _this.webVROptions.trackPosition = true;
  79189. }
  79190. if (_this.webVROptions.controllerMeshes == undefined) {
  79191. _this.webVROptions.controllerMeshes = true;
  79192. }
  79193. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79194. _this.webVROptions.defaultLightingOnControllers = true;
  79195. }
  79196. _this.rotationQuaternion = new BABYLON.Quaternion();
  79197. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79198. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79199. }
  79200. //enable VR
  79201. var engine = _this.getEngine();
  79202. _this._onVREnabled = function (success) { if (success) {
  79203. _this.initControllers();
  79204. } };
  79205. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79206. engine.initWebVR().add(function (event) {
  79207. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79208. return;
  79209. }
  79210. _this._vrDevice = event.vrDisplay;
  79211. //reset the rig parameters.
  79212. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79213. if (_this._attached) {
  79214. _this.getEngine().enableVR();
  79215. }
  79216. });
  79217. if (typeof (VRFrameData) !== "undefined")
  79218. _this._frameData = new VRFrameData();
  79219. /**
  79220. * The idea behind the following lines:
  79221. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79222. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79223. * the second will not show it correctly.
  79224. *
  79225. * To solve this - each object that has the camera as parent will be added to a protected array.
  79226. * When the rig camera renders, it will take this array and set all of those to be its children.
  79227. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79228. * Amazing!
  79229. */
  79230. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79231. if (camera.parent === _this && _this.rigParenting) {
  79232. _this._descendants = _this.getDescendants(true, function (n) {
  79233. // don't take the cameras or the controllers!
  79234. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79235. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79236. return !isController && !isRigCamera;
  79237. });
  79238. _this._descendants.forEach(function (node) {
  79239. node.parent = camera;
  79240. });
  79241. }
  79242. });
  79243. scene.onAfterCameraRenderObservable.add(function (camera) {
  79244. if (camera.parent === _this && _this.rigParenting) {
  79245. _this._descendants.forEach(function (node) {
  79246. node.parent = _this;
  79247. });
  79248. }
  79249. });
  79250. return _this;
  79251. }
  79252. /**
  79253. * Gets the device distance from the ground in meters.
  79254. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  79255. */
  79256. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79257. if (this._standingMatrix) {
  79258. // Add standing matrix offset to get real offset from ground in room
  79259. this._standingMatrix.getTranslationToRef(this._workingVector);
  79260. return this._deviceRoomPosition.y + this._workingVector.y;
  79261. }
  79262. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79263. return this._defaultHeight || 0;
  79264. };
  79265. /**
  79266. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79267. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79268. */
  79269. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79270. var _this = this;
  79271. if (callback === void 0) { callback = function (bool) { }; }
  79272. // Use standing matrix if available
  79273. this.getEngine().initWebVRAsync().then(function (result) {
  79274. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79275. callback(false);
  79276. }
  79277. else {
  79278. _this._standingMatrix = new BABYLON.Matrix();
  79279. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79280. if (!_this.getScene().useRightHandedSystem) {
  79281. [2, 6, 8, 9, 14].forEach(function (num) {
  79282. if (_this._standingMatrix) {
  79283. _this._standingMatrix.m[num] *= -1;
  79284. }
  79285. });
  79286. }
  79287. callback(true);
  79288. }
  79289. });
  79290. };
  79291. /**
  79292. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79293. * @returns A promise with a boolean set to if the standing matrix is supported.
  79294. */
  79295. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79296. var _this = this;
  79297. return new Promise(function (res, rej) {
  79298. _this.useStandingMatrix(function (supported) {
  79299. res(supported);
  79300. });
  79301. });
  79302. };
  79303. /**
  79304. * Disposes the camera
  79305. */
  79306. WebVRFreeCamera.prototype.dispose = function () {
  79307. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79308. _super.prototype.dispose.call(this);
  79309. };
  79310. /**
  79311. * Gets a vrController by name.
  79312. * @param name The name of the controller to retreive
  79313. * @returns the controller matching the name specified or null if not found
  79314. */
  79315. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79316. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79317. var gp = _a[_i];
  79318. if (gp.hand === name) {
  79319. return gp;
  79320. }
  79321. }
  79322. return null;
  79323. };
  79324. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79325. /**
  79326. * The controller corrisponding to the users left hand.
  79327. */
  79328. get: function () {
  79329. if (!this._leftController) {
  79330. this._leftController = this.getControllerByName("left");
  79331. }
  79332. return this._leftController;
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. ;
  79338. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79339. /**
  79340. * The controller corrisponding to the users right hand.
  79341. */
  79342. get: function () {
  79343. if (!this._rightController) {
  79344. this._rightController = this.getControllerByName("right");
  79345. }
  79346. return this._rightController;
  79347. },
  79348. enumerable: true,
  79349. configurable: true
  79350. });
  79351. ;
  79352. /**
  79353. * Casts a ray forward from the vrCamera's gaze.
  79354. * @param length Length of the ray (default: 100)
  79355. * @returns the ray corrisponding to the gaze
  79356. */
  79357. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79358. if (length === void 0) { length = 100; }
  79359. if (this.leftCamera) {
  79360. // Use left eye to avoid computation to compute center on every call
  79361. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79362. }
  79363. else {
  79364. return _super.prototype.getForwardRay.call(this, length);
  79365. }
  79366. };
  79367. /**
  79368. * Updates the camera based on device's frame data
  79369. */
  79370. WebVRFreeCamera.prototype._checkInputs = function () {
  79371. if (this._vrDevice && this._vrDevice.isPresenting) {
  79372. this._vrDevice.getFrameData(this._frameData);
  79373. this.updateFromDevice(this._frameData.pose);
  79374. }
  79375. _super.prototype._checkInputs.call(this);
  79376. };
  79377. /**
  79378. * Updates the poseControlled values based on the input device pose.
  79379. * @param poseData Pose coming from the device
  79380. */
  79381. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79382. if (poseData && poseData.orientation) {
  79383. this.rawPose = poseData;
  79384. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79385. if (this.getScene().useRightHandedSystem) {
  79386. this._deviceRoomRotationQuaternion.z *= -1;
  79387. this._deviceRoomRotationQuaternion.w *= -1;
  79388. }
  79389. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79390. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79391. if (this.getScene().useRightHandedSystem) {
  79392. this._deviceRoomPosition.z *= -1;
  79393. }
  79394. }
  79395. }
  79396. };
  79397. /**
  79398. * WebVR's attach control will start broadcasting frames to the device.
  79399. * Note that in certain browsers (chrome for example) this function must be called
  79400. * within a user-interaction callback. Example:
  79401. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79402. *
  79403. * @param element html element to attach the vrDevice to
  79404. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79405. */
  79406. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79407. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79408. this._attached = true;
  79409. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79410. if (this._vrDevice) {
  79411. this.getEngine().enableVR();
  79412. }
  79413. };
  79414. /**
  79415. * Detaches the camera from the html element and disables VR
  79416. *
  79417. * @param element html element to detach from
  79418. */
  79419. WebVRFreeCamera.prototype.detachControl = function (element) {
  79420. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79421. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79422. _super.prototype.detachControl.call(this, element);
  79423. this._attached = false;
  79424. this.getEngine().disableVR();
  79425. };
  79426. /**
  79427. * @returns the name of this class
  79428. */
  79429. WebVRFreeCamera.prototype.getClassName = function () {
  79430. return "WebVRFreeCamera";
  79431. };
  79432. /**
  79433. * Calls resetPose on the vrDisplay
  79434. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79435. */
  79436. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79437. //uses the vrDisplay's "resetPose()".
  79438. //pitch and roll won't be affected.
  79439. this._vrDevice.resetPose();
  79440. };
  79441. /**
  79442. * Updates the rig cameras (left and right eye)
  79443. */
  79444. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79445. var camLeft = this._rigCameras[0];
  79446. var camRight = this._rigCameras[1];
  79447. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79448. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79449. camLeft.position.copyFrom(this._deviceRoomPosition);
  79450. camRight.position.copyFrom(this._deviceRoomPosition);
  79451. };
  79452. /**
  79453. * Updates the cached values of the camera
  79454. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79455. */
  79456. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79457. var _this = this;
  79458. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79459. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79460. if (!this.updateCacheCalled) {
  79461. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79462. this.updateCacheCalled = true;
  79463. this.update();
  79464. }
  79465. // Set working vector to the device position in room space rotated by the new rotation
  79466. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79467. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79468. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79469. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79470. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79471. // Add translation from anchor position
  79472. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79473. this._workingVector.addInPlace(this.position);
  79474. this._workingVector.subtractInPlace(this._cache.position);
  79475. this._deviceToWorld.setTranslation(this._workingVector);
  79476. // Set an inverted matrix to be used when updating the camera
  79477. this._deviceToWorld.invertToRef(this._worldToDevice);
  79478. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79479. this.controllers.forEach(function (controller) {
  79480. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79481. controller.update();
  79482. });
  79483. }
  79484. if (!ignoreParentClass) {
  79485. _super.prototype._updateCache.call(this);
  79486. }
  79487. this.updateCacheCalled = false;
  79488. };
  79489. /**
  79490. * Updates the current device position and rotation in the babylon world
  79491. */
  79492. WebVRFreeCamera.prototype.update = function () {
  79493. // Get current device position in babylon world
  79494. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79495. // Get current device rotation in babylon world
  79496. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79497. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79498. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79499. _super.prototype.update.call(this);
  79500. };
  79501. /**
  79502. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79503. * @returns an identity matrix
  79504. */
  79505. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79506. return BABYLON.Matrix.Identity();
  79507. };
  79508. /**
  79509. * This function is called by the two RIG cameras.
  79510. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79511. */
  79512. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79513. var _this = this;
  79514. // Update the parent camera prior to using a child camera to avoid desynchronization
  79515. var parentCamera = this._cameraRigParams["parentCamera"];
  79516. parentCamera._updateCache();
  79517. //WebVR 1.1
  79518. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79519. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79520. if (!this.getScene().useRightHandedSystem) {
  79521. [2, 6, 8, 9, 14].forEach(function (num) {
  79522. _this._webvrViewMatrix.m[num] *= -1;
  79523. });
  79524. }
  79525. // update the camera rotation matrix
  79526. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79527. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79528. // Computing target and final matrix
  79529. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79530. // should the view matrix be updated with scale and position offset?
  79531. if (parentCamera.deviceScaleFactor !== 1) {
  79532. this._webvrViewMatrix.invert();
  79533. // scale the position, if set
  79534. if (parentCamera.deviceScaleFactor) {
  79535. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79536. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79537. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79538. }
  79539. this._webvrViewMatrix.invert();
  79540. }
  79541. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79542. return this._webvrViewMatrix;
  79543. };
  79544. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79545. var _this = this;
  79546. var parentCamera = this.parent;
  79547. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79548. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79549. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79550. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79551. //babylon compatible matrix
  79552. if (!this.getScene().useRightHandedSystem) {
  79553. [8, 9, 10, 11].forEach(function (num) {
  79554. _this._projectionMatrix.m[num] *= -1;
  79555. });
  79556. }
  79557. return this._projectionMatrix;
  79558. };
  79559. /**
  79560. * Initializes the controllers and their meshes
  79561. */
  79562. WebVRFreeCamera.prototype.initControllers = function () {
  79563. var _this = this;
  79564. this.controllers = [];
  79565. var manager = this.getScene().gamepadManager;
  79566. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79567. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79568. var webVrController = gamepad;
  79569. if (webVrController.defaultModel) {
  79570. webVrController.defaultModel.setEnabled(false);
  79571. }
  79572. if (webVrController.hand === "right") {
  79573. _this._rightController = null;
  79574. }
  79575. if (webVrController.hand === "left") {
  79576. _this._leftController = null;
  79577. }
  79578. var controllerIndex = _this.controllers.indexOf(webVrController);
  79579. if (controllerIndex !== -1) {
  79580. _this.controllers.splice(controllerIndex, 1);
  79581. }
  79582. }
  79583. });
  79584. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79585. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79586. var webVrController_1 = gamepad;
  79587. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79588. if (_this.webVROptions.controllerMeshes) {
  79589. if (webVrController_1.defaultModel) {
  79590. webVrController_1.defaultModel.setEnabled(true);
  79591. }
  79592. else {
  79593. // Load the meshes
  79594. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79595. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79596. if (_this.webVROptions.defaultLightingOnControllers) {
  79597. if (!_this._lightOnControllers) {
  79598. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79599. }
  79600. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79601. var children = mesh.getChildren();
  79602. if (children.length !== 0) {
  79603. children.forEach(function (mesh) {
  79604. light.includedOnlyMeshes.push(mesh);
  79605. activateLightOnSubMeshes_1(mesh, light);
  79606. });
  79607. }
  79608. };
  79609. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79610. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79611. }
  79612. });
  79613. }
  79614. }
  79615. webVrController_1.attachToPoseControlledCamera(_this);
  79616. // since this is async - sanity check. Is the controller already stored?
  79617. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79618. //add to the controllers array
  79619. _this.controllers.push(webVrController_1);
  79620. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79621. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79622. // So we're overriding setting left & right manually to be sure
  79623. var firstViveWandDetected = false;
  79624. for (var i = 0; i < _this.controllers.length; i++) {
  79625. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79626. if (!firstViveWandDetected) {
  79627. firstViveWandDetected = true;
  79628. _this.controllers[i].hand = "left";
  79629. }
  79630. else {
  79631. _this.controllers[i].hand = "right";
  79632. }
  79633. }
  79634. }
  79635. //did we find enough controllers? Great! let the developer know.
  79636. if (_this.controllers.length >= 2) {
  79637. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79638. }
  79639. }
  79640. }
  79641. });
  79642. };
  79643. return WebVRFreeCamera;
  79644. }(BABYLON.FreeCamera));
  79645. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79646. })(BABYLON || (BABYLON = {}));
  79647. //# sourceMappingURL=babylon.webVRCamera.js.map
  79648. var BABYLON;
  79649. (function (BABYLON) {
  79650. // We're mainly based on the logic defined into the FreeCamera code
  79651. /**
  79652. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79653. * being tilted forward or back and left or right.
  79654. */
  79655. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79656. __extends(DeviceOrientationCamera, _super);
  79657. /**
  79658. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79659. * @param name The name of the camera
  79660. * @param position The start position camera
  79661. * @param scene The scene the camera belongs to
  79662. */
  79663. function DeviceOrientationCamera(name, position, scene) {
  79664. var _this = _super.call(this, name, position, scene) || this;
  79665. _this._quaternionCache = new BABYLON.Quaternion();
  79666. _this.inputs.addDeviceOrientation();
  79667. return _this;
  79668. }
  79669. /**
  79670. * Gets the current instance class name ("DeviceOrientationCamera").
  79671. * This helps avoiding instanceof at run time.
  79672. * @returns the class name
  79673. */
  79674. DeviceOrientationCamera.prototype.getClassName = function () {
  79675. return "DeviceOrientationCamera";
  79676. };
  79677. /**
  79678. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79679. */
  79680. DeviceOrientationCamera.prototype._checkInputs = function () {
  79681. _super.prototype._checkInputs.call(this);
  79682. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79683. if (this._initialQuaternion) {
  79684. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79685. }
  79686. };
  79687. /**
  79688. * Reset the camera to its default orientation on the specified axis only.
  79689. * @param axis The axis to reset
  79690. */
  79691. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79692. var _this = this;
  79693. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79694. //can only work if this camera has a rotation quaternion already.
  79695. if (!this.rotationQuaternion)
  79696. return;
  79697. if (!this._initialQuaternion) {
  79698. this._initialQuaternion = new BABYLON.Quaternion();
  79699. }
  79700. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79701. ['x', 'y', 'z'].forEach(function (axisName) {
  79702. if (!axis[axisName]) {
  79703. _this._initialQuaternion[axisName] = 0;
  79704. }
  79705. else {
  79706. _this._initialQuaternion[axisName] *= -1;
  79707. }
  79708. });
  79709. this._initialQuaternion.normalize();
  79710. //force rotation update
  79711. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79712. };
  79713. return DeviceOrientationCamera;
  79714. }(BABYLON.FreeCamera));
  79715. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79716. })(BABYLON || (BABYLON = {}));
  79717. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79718. var BABYLON;
  79719. (function (BABYLON) {
  79720. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79721. __extends(VRDeviceOrientationFreeCamera, _super);
  79722. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79723. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79724. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79725. var _this = _super.call(this, name, position, scene) || this;
  79726. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79727. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79728. return _this;
  79729. }
  79730. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79731. return "VRDeviceOrientationFreeCamera";
  79732. };
  79733. return VRDeviceOrientationFreeCamera;
  79734. }(BABYLON.DeviceOrientationCamera));
  79735. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79736. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79737. __extends(VRDeviceOrientationGamepadCamera, _super);
  79738. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79739. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79740. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79741. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79742. _this.inputs.addGamepad();
  79743. return _this;
  79744. }
  79745. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79746. return "VRDeviceOrientationGamepadCamera";
  79747. };
  79748. return VRDeviceOrientationGamepadCamera;
  79749. }(VRDeviceOrientationFreeCamera));
  79750. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79751. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79752. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79753. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79754. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79755. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79756. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79757. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79758. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79759. _this.inputs.addVRDeviceOrientation();
  79760. return _this;
  79761. }
  79762. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79763. return "VRDeviceOrientationArcRotateCamera";
  79764. };
  79765. return VRDeviceOrientationArcRotateCamera;
  79766. }(BABYLON.ArcRotateCamera));
  79767. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79768. })(BABYLON || (BABYLON = {}));
  79769. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79770. var BABYLON;
  79771. (function (BABYLON) {
  79772. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79773. __extends(AnaglyphFreeCamera, _super);
  79774. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79775. var _this = _super.call(this, name, position, scene) || this;
  79776. _this.interaxialDistance = interaxialDistance;
  79777. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79778. return _this;
  79779. }
  79780. AnaglyphFreeCamera.prototype.getClassName = function () {
  79781. return "AnaglyphFreeCamera";
  79782. };
  79783. return AnaglyphFreeCamera;
  79784. }(BABYLON.FreeCamera));
  79785. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79786. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79787. __extends(AnaglyphArcRotateCamera, _super);
  79788. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79789. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79790. _this.interaxialDistance = interaxialDistance;
  79791. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79792. return _this;
  79793. }
  79794. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79795. return "AnaglyphArcRotateCamera";
  79796. };
  79797. return AnaglyphArcRotateCamera;
  79798. }(BABYLON.ArcRotateCamera));
  79799. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79800. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79801. __extends(AnaglyphGamepadCamera, _super);
  79802. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79803. var _this = _super.call(this, name, position, scene) || this;
  79804. _this.interaxialDistance = interaxialDistance;
  79805. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79806. return _this;
  79807. }
  79808. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79809. return "AnaglyphGamepadCamera";
  79810. };
  79811. return AnaglyphGamepadCamera;
  79812. }(BABYLON.GamepadCamera));
  79813. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79814. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79815. __extends(AnaglyphUniversalCamera, _super);
  79816. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79817. var _this = _super.call(this, name, position, scene) || this;
  79818. _this.interaxialDistance = interaxialDistance;
  79819. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79820. return _this;
  79821. }
  79822. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79823. return "AnaglyphUniversalCamera";
  79824. };
  79825. return AnaglyphUniversalCamera;
  79826. }(BABYLON.UniversalCamera));
  79827. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79828. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79829. __extends(StereoscopicFreeCamera, _super);
  79830. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79831. var _this = _super.call(this, name, position, scene) || this;
  79832. _this.interaxialDistance = interaxialDistance;
  79833. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79834. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79835. return _this;
  79836. }
  79837. StereoscopicFreeCamera.prototype.getClassName = function () {
  79838. return "StereoscopicFreeCamera";
  79839. };
  79840. return StereoscopicFreeCamera;
  79841. }(BABYLON.FreeCamera));
  79842. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79843. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79844. __extends(StereoscopicArcRotateCamera, _super);
  79845. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79846. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79847. _this.interaxialDistance = interaxialDistance;
  79848. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79849. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79850. return _this;
  79851. }
  79852. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79853. return "StereoscopicArcRotateCamera";
  79854. };
  79855. return StereoscopicArcRotateCamera;
  79856. }(BABYLON.ArcRotateCamera));
  79857. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79858. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79859. __extends(StereoscopicGamepadCamera, _super);
  79860. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79861. var _this = _super.call(this, name, position, scene) || this;
  79862. _this.interaxialDistance = interaxialDistance;
  79863. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79864. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79865. return _this;
  79866. }
  79867. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79868. return "StereoscopicGamepadCamera";
  79869. };
  79870. return StereoscopicGamepadCamera;
  79871. }(BABYLON.GamepadCamera));
  79872. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79873. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79874. __extends(StereoscopicUniversalCamera, _super);
  79875. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79876. var _this = _super.call(this, name, position, scene) || this;
  79877. _this.interaxialDistance = interaxialDistance;
  79878. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79879. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79880. return _this;
  79881. }
  79882. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79883. return "StereoscopicUniversalCamera";
  79884. };
  79885. return StereoscopicUniversalCamera;
  79886. }(BABYLON.UniversalCamera));
  79887. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79888. })(BABYLON || (BABYLON = {}));
  79889. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79890. var BABYLON;
  79891. (function (BABYLON) {
  79892. var VRExperienceHelperGazer = /** @class */ (function () {
  79893. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  79894. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  79895. this.scene = scene;
  79896. this._pointerDownOnMeshAsked = false;
  79897. this._isActionableMesh = false;
  79898. this._teleportationRequestInitiated = false;
  79899. this._teleportationBackRequestInitiated = false;
  79900. this._dpadPressed = true;
  79901. this._activePointer = false;
  79902. this._id = VRExperienceHelperGazer._idCounter++;
  79903. // Gaze tracker
  79904. if (!gazeTrackerToClone) {
  79905. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  79906. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79907. this._gazeTracker.isPickable = false;
  79908. this._gazeTracker.isVisible = false;
  79909. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  79910. targetMat.specularColor = BABYLON.Color3.Black();
  79911. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79912. targetMat.backFaceCulling = false;
  79913. this._gazeTracker.material = targetMat;
  79914. }
  79915. else {
  79916. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  79917. }
  79918. }
  79919. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  79920. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  79921. };
  79922. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  79923. this._pointerDownOnMeshAsked = true;
  79924. if (this._currentMeshSelected && this._currentHit) {
  79925. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  79926. }
  79927. };
  79928. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  79929. if (this._currentMeshSelected && this._currentHit) {
  79930. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  79931. }
  79932. this._pointerDownOnMeshAsked = false;
  79933. };
  79934. VRExperienceHelperGazer.prototype._activatePointer = function () {
  79935. this._activePointer = true;
  79936. };
  79937. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  79938. this._activePointer = false;
  79939. };
  79940. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  79941. };
  79942. VRExperienceHelperGazer.prototype.dispose = function () {
  79943. this._interactionsEnabled = false;
  79944. this._teleportationEnabled = false;
  79945. };
  79946. VRExperienceHelperGazer._idCounter = 0;
  79947. return VRExperienceHelperGazer;
  79948. }());
  79949. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  79950. __extends(VRExperienceHelperControllerGazer, _super);
  79951. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  79952. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  79953. _this.webVRController = webVRController;
  79954. // Laser pointer
  79955. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  79956. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  79957. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79958. laserPointerMaterial.alpha = 0.6;
  79959. _this._laserPointer.material = laserPointerMaterial;
  79960. _this._laserPointer.rotation.x = Math.PI / 2;
  79961. _this._laserPointer.position.z = -0.5;
  79962. _this._laserPointer.isVisible = false;
  79963. _this._laserPointer.parent = webVRController.mesh;
  79964. return _this;
  79965. }
  79966. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  79967. return this.webVRController.getForwardRay(length);
  79968. };
  79969. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  79970. _super.prototype._activatePointer.call(this);
  79971. this._laserPointer.isVisible = true;
  79972. };
  79973. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  79974. _super.prototype._deactivatePointer.call(this);
  79975. this._laserPointer.isVisible = false;
  79976. };
  79977. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  79978. this._laserPointer.material.emissiveColor = color;
  79979. };
  79980. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  79981. this._laserPointer.parent = mesh;
  79982. };
  79983. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  79984. this._laserPointer.scaling.y = distance;
  79985. this._laserPointer.position.z = -distance / 2;
  79986. };
  79987. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  79988. _super.prototype.dispose.call(this);
  79989. this._laserPointer.dispose();
  79990. };
  79991. return VRExperienceHelperControllerGazer;
  79992. }(VRExperienceHelperGazer));
  79993. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  79994. __extends(VRExperienceHelperCameraGazer, _super);
  79995. function VRExperienceHelperCameraGazer(getCamera, scene) {
  79996. var _this = _super.call(this, scene) || this;
  79997. _this.getCamera = getCamera;
  79998. return _this;
  79999. }
  80000. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80001. var camera = this.getCamera();
  80002. if (camera) {
  80003. return camera.getForwardRay(length);
  80004. }
  80005. else {
  80006. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80007. }
  80008. };
  80009. return VRExperienceHelperCameraGazer;
  80010. }(VRExperienceHelperGazer));
  80011. /**
  80012. * Helps to quickly add VR support to an existing scene.
  80013. * See http://doc.babylonjs.com/how_to/webvr_helper
  80014. */
  80015. var VRExperienceHelper = /** @class */ (function () {
  80016. /**
  80017. * Instantiates a VRExperienceHelper.
  80018. * Helps to quickly add VR support to an existing scene.
  80019. * @param scene The scene the VRExperienceHelper belongs to.
  80020. * @param webVROptions Options to modify the vr experience helper's behavior.
  80021. */
  80022. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80023. if (webVROptions === void 0) { webVROptions = {}; }
  80024. var _this = this;
  80025. this.webVROptions = webVROptions;
  80026. // Can the system support WebVR, even if a headset isn't plugged in?
  80027. this._webVRsupported = false;
  80028. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80029. this._webVRready = false;
  80030. // Are we waiting for the requestPresent callback to complete?
  80031. this._webVRrequesting = false;
  80032. // Are we presenting to the headset right now?
  80033. this._webVRpresenting = false;
  80034. // Are we presenting in the fullscreen fallback?
  80035. this._fullscreenVRpresenting = false;
  80036. /**
  80037. * Observable raised when entering VR.
  80038. */
  80039. this.onEnteringVRObservable = new BABYLON.Observable();
  80040. /**
  80041. * Observable raised when exiting VR.
  80042. */
  80043. this.onExitingVRObservable = new BABYLON.Observable();
  80044. /**
  80045. * Observable raised when controller mesh is loaded.
  80046. */
  80047. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80048. this._useCustomVRButton = false;
  80049. this._teleportationRequested = false;
  80050. this._teleportActive = false;
  80051. this._floorMeshesCollection = [];
  80052. this._rotationAllowed = true;
  80053. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80054. this._rotationRightAsked = false;
  80055. this._rotationLeftAsked = false;
  80056. this._isDefaultTeleportationTarget = true;
  80057. this._teleportationFillColor = "#444444";
  80058. this._teleportationBorderColor = "#FFFFFF";
  80059. this._rotationAngle = 0;
  80060. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80061. this._padSensibilityUp = 0.65;
  80062. this._padSensibilityDown = 0.35;
  80063. this.leftController = null;
  80064. this.rightController = null;
  80065. /**
  80066. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80067. */
  80068. this.onNewMeshSelected = new BABYLON.Observable();
  80069. /**
  80070. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80071. */
  80072. this.onNewMeshPicked = new BABYLON.Observable();
  80073. /**
  80074. * Observable raised before camera teleportation
  80075. */
  80076. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80077. /**
  80078. * Observable raised after camera teleportation
  80079. */
  80080. this.onAfterCameraTeleport = new BABYLON.Observable();
  80081. /**
  80082. * Observable raised when current selected mesh gets unselected
  80083. */
  80084. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80085. /**
  80086. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80087. */
  80088. this.teleportationEnabled = true;
  80089. this._teleportationInitialized = false;
  80090. this._interactionsEnabled = false;
  80091. this._interactionsRequested = false;
  80092. this._displayGaze = true;
  80093. this._displayLaserPointer = true;
  80094. this._onResize = function () {
  80095. _this.moveButtonToBottomRight();
  80096. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80097. _this.exitVR();
  80098. }
  80099. };
  80100. this._onFullscreenChange = function () {
  80101. if (document.fullscreen !== undefined) {
  80102. _this._fullscreenVRpresenting = document.fullscreen;
  80103. }
  80104. else if (document.mozFullScreen !== undefined) {
  80105. _this._fullscreenVRpresenting = document.mozFullScreen;
  80106. }
  80107. else if (document.webkitIsFullScreen !== undefined) {
  80108. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80109. }
  80110. else if (document.msIsFullScreen !== undefined) {
  80111. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80112. }
  80113. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80114. _this.exitVR();
  80115. if (!_this._useCustomVRButton) {
  80116. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80117. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80118. }
  80119. }
  80120. };
  80121. this.beforeRender = function () {
  80122. if (_this.leftController && _this.leftController._activePointer) {
  80123. _this._castRayAndSelectObject(_this.leftController);
  80124. }
  80125. if (_this.rightController && _this.rightController._activePointer) {
  80126. _this._castRayAndSelectObject(_this.rightController);
  80127. }
  80128. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80129. _this._castRayAndSelectObject(_this._cameraGazer);
  80130. }
  80131. else {
  80132. _this._cameraGazer._gazeTracker.isVisible = false;
  80133. }
  80134. };
  80135. this._onNewGamepadConnected = function (gamepad) {
  80136. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80137. if (gamepad.leftStick) {
  80138. gamepad.onleftstickchanged(function (stickValues) {
  80139. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80140. // Listening to classic/xbox gamepad only if no VR controller is active
  80141. if ((!_this.leftController && !_this.rightController) ||
  80142. ((_this.leftController && !_this.leftController._activePointer) &&
  80143. (_this.rightController && !_this.rightController._activePointer))) {
  80144. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80145. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80146. }
  80147. }
  80148. });
  80149. }
  80150. if (gamepad.rightStick) {
  80151. gamepad.onrightstickchanged(function (stickValues) {
  80152. if (_this._teleportationInitialized) {
  80153. _this._checkRotate(stickValues, _this._cameraGazer);
  80154. }
  80155. });
  80156. }
  80157. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80158. gamepad.onbuttondown(function (buttonPressed) {
  80159. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80160. _this._cameraGazer._selectionPointerDown();
  80161. }
  80162. });
  80163. gamepad.onbuttonup(function (buttonPressed) {
  80164. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80165. _this._cameraGazer._selectionPointerUp();
  80166. }
  80167. });
  80168. }
  80169. }
  80170. else {
  80171. var webVRController = gamepad;
  80172. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80173. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80174. _this.rightController = controller;
  80175. }
  80176. else {
  80177. _this.leftController = controller;
  80178. }
  80179. _this._tryEnableInteractionOnController(controller);
  80180. }
  80181. };
  80182. // 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
  80183. this._tryEnableInteractionOnController = function (controller) {
  80184. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80185. _this._enableInteractionOnController(controller);
  80186. }
  80187. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80188. _this._enableTeleportationOnController(controller);
  80189. }
  80190. };
  80191. this._onNewGamepadDisconnected = function (gamepad) {
  80192. if (gamepad instanceof BABYLON.WebVRController) {
  80193. if (gamepad.hand === "left" && _this.leftController != null) {
  80194. _this.leftController.dispose();
  80195. _this.leftController = null;
  80196. }
  80197. if (gamepad.hand === "right" && _this.rightController != null) {
  80198. _this.rightController.dispose();
  80199. _this.rightController = null;
  80200. }
  80201. }
  80202. };
  80203. this._workingVector = BABYLON.Vector3.Zero();
  80204. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80205. this._workingMatrix = BABYLON.Matrix.Identity();
  80206. this._scene = scene;
  80207. this._canvas = scene.getEngine().getRenderingCanvas();
  80208. // Parse options
  80209. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80210. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80211. }
  80212. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80213. webVROptions.createDeviceOrientationCamera = true;
  80214. }
  80215. if (webVROptions.defaultHeight === undefined) {
  80216. webVROptions.defaultHeight = 1.7;
  80217. }
  80218. if (webVROptions.useCustomVRButton) {
  80219. this._useCustomVRButton = true;
  80220. if (webVROptions.customVRButton) {
  80221. this._btnVR = webVROptions.customVRButton;
  80222. }
  80223. }
  80224. if (webVROptions.rayLength) {
  80225. this._rayLength = webVROptions.rayLength;
  80226. }
  80227. this._defaultHeight = webVROptions.defaultHeight;
  80228. // Set position
  80229. if (this._scene.activeCamera) {
  80230. this._position = this._scene.activeCamera.position.clone();
  80231. }
  80232. else {
  80233. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80234. }
  80235. // Set non-vr camera
  80236. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80237. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80238. // Copy data from existing camera
  80239. if (this._scene.activeCamera) {
  80240. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80241. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80242. // Set rotation from previous camera
  80243. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80244. var targetCamera = this._scene.activeCamera;
  80245. if (targetCamera.rotationQuaternion) {
  80246. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80247. }
  80248. else {
  80249. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80250. }
  80251. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80252. }
  80253. }
  80254. this._scene.activeCamera = this._deviceOrientationCamera;
  80255. if (this._canvas) {
  80256. this._scene.activeCamera.attachControl(this._canvas);
  80257. }
  80258. }
  80259. else {
  80260. this._existingCamera = this._scene.activeCamera;
  80261. }
  80262. // Create VR cameras
  80263. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80264. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80265. }
  80266. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80267. this._webVRCamera.useStandingMatrix();
  80268. // Create default button
  80269. if (!this._useCustomVRButton) {
  80270. this._btnVR = document.createElement("BUTTON");
  80271. this._btnVR.className = "babylonVRicon";
  80272. this._btnVR.id = "babylonVRiconbtn";
  80273. this._btnVR.title = "Click to switch to VR";
  80274. 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) }";
  80275. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80276. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80277. // css += ".babylonVRicon.vrdisplaysupported { }";
  80278. // css += ".babylonVRicon.vrdisplayready { }";
  80279. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80280. var style = document.createElement('style');
  80281. style.appendChild(document.createTextNode(css));
  80282. document.getElementsByTagName('head')[0].appendChild(style);
  80283. this.moveButtonToBottomRight();
  80284. }
  80285. // VR button click event
  80286. if (this._btnVR) {
  80287. this._btnVR.addEventListener("click", function () {
  80288. if (!_this.isInVRMode) {
  80289. _this.enterVR();
  80290. }
  80291. else {
  80292. _this.exitVR();
  80293. }
  80294. });
  80295. }
  80296. // Window events
  80297. window.addEventListener("resize", this._onResize);
  80298. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80299. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80300. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80301. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80302. // Display vr button when headset is connected
  80303. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80304. this.displayVRButton();
  80305. }
  80306. else {
  80307. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80308. if (e.vrDisplay) {
  80309. _this.displayVRButton();
  80310. }
  80311. });
  80312. }
  80313. // Exiting VR mode using 'ESC' key on desktop
  80314. this._onKeyDown = function (event) {
  80315. if (event.keyCode === 27 && _this.isInVRMode) {
  80316. _this.exitVR();
  80317. }
  80318. };
  80319. document.addEventListener("keydown", this._onKeyDown);
  80320. // Exiting VR mode double tapping the touch screen
  80321. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80322. if (_this.isInVRMode) {
  80323. _this.exitVR();
  80324. if (_this._fullscreenVRpresenting) {
  80325. _this._scene.getEngine().switchFullscreen(true);
  80326. }
  80327. }
  80328. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80329. // Listen for WebVR display changes
  80330. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80331. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80332. this._onVRRequestPresentStart = function () {
  80333. _this._webVRrequesting = true;
  80334. _this.updateButtonVisibility();
  80335. };
  80336. this._onVRRequestPresentComplete = function (success) {
  80337. _this._webVRrequesting = false;
  80338. _this.updateButtonVisibility();
  80339. };
  80340. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80341. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80342. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80343. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80344. scene.onDisposeObservable.add(function () {
  80345. _this.dispose();
  80346. });
  80347. // Gamepad connection events
  80348. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80349. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80350. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80351. this.updateButtonVisibility();
  80352. //create easing functions
  80353. this._circleEase = new BABYLON.CircleEase();
  80354. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80355. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80356. }
  80357. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80358. /** Return this.onEnteringVRObservable
  80359. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80360. */
  80361. get: function () {
  80362. return this.onEnteringVRObservable;
  80363. },
  80364. enumerable: true,
  80365. configurable: true
  80366. });
  80367. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80368. /** Return this.onExitingVRObservable
  80369. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80370. */
  80371. get: function () {
  80372. return this.onExitingVRObservable;
  80373. },
  80374. enumerable: true,
  80375. configurable: true
  80376. });
  80377. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80378. /** Return this.onControllerMeshLoadedObservable
  80379. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80380. */
  80381. get: function () {
  80382. return this.onControllerMeshLoadedObservable;
  80383. },
  80384. enumerable: true,
  80385. configurable: true
  80386. });
  80387. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80388. /**
  80389. * The mesh used to display where the user is going to teleport.
  80390. */
  80391. get: function () {
  80392. return this._teleportationTarget;
  80393. },
  80394. /**
  80395. * Sets the mesh to be used to display where the user is going to teleport.
  80396. */
  80397. set: function (value) {
  80398. if (value) {
  80399. value.name = "teleportationTarget";
  80400. this._isDefaultTeleportationTarget = false;
  80401. this._teleportationTarget = value;
  80402. }
  80403. },
  80404. enumerable: true,
  80405. configurable: true
  80406. });
  80407. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80408. /**
  80409. * The mesh used to display where the user is selecting,
  80410. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80411. * See http://doc.babylonjs.com/resources/baking_transformations
  80412. */
  80413. get: function () {
  80414. return this._cameraGazer._gazeTracker;
  80415. },
  80416. set: function (value) {
  80417. if (value) {
  80418. this._cameraGazer._gazeTracker = value;
  80419. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80420. this._cameraGazer._gazeTracker.isPickable = false;
  80421. this._cameraGazer._gazeTracker.isVisible = false;
  80422. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80423. if (this.leftController) {
  80424. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80425. }
  80426. if (this.rightController) {
  80427. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80428. }
  80429. }
  80430. },
  80431. enumerable: true,
  80432. configurable: true
  80433. });
  80434. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80435. /**
  80436. * If the ray of the gaze should be displayed.
  80437. */
  80438. get: function () {
  80439. return this._displayGaze;
  80440. },
  80441. /**
  80442. * Sets if the ray of the gaze should be displayed.
  80443. */
  80444. set: function (value) {
  80445. this._displayGaze = value;
  80446. if (!value) {
  80447. this._cameraGazer._gazeTracker.isVisible = false;
  80448. if (this.leftController) {
  80449. this.leftController._gazeTracker.isVisible = false;
  80450. }
  80451. if (this.rightController) {
  80452. this.rightController._gazeTracker.isVisible = false;
  80453. }
  80454. }
  80455. },
  80456. enumerable: true,
  80457. configurable: true
  80458. });
  80459. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80460. /**
  80461. * If the ray of the LaserPointer should be displayed.
  80462. */
  80463. get: function () {
  80464. return this._displayLaserPointer;
  80465. },
  80466. /**
  80467. * Sets if the ray of the LaserPointer should be displayed.
  80468. */
  80469. set: function (value) {
  80470. this._displayLaserPointer = value;
  80471. if (!value) {
  80472. if (this.rightController) {
  80473. this.rightController._deactivatePointer();
  80474. this.rightController._gazeTracker.isVisible = false;
  80475. }
  80476. if (this.leftController) {
  80477. this.leftController._deactivatePointer();
  80478. this.leftController._gazeTracker.isVisible = false;
  80479. }
  80480. }
  80481. else {
  80482. if (this.rightController) {
  80483. this.rightController._activatePointer();
  80484. }
  80485. else if (this.leftController) {
  80486. this.leftController._activatePointer();
  80487. }
  80488. }
  80489. },
  80490. enumerable: true,
  80491. configurable: true
  80492. });
  80493. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80494. /**
  80495. * The deviceOrientationCamera used as the camera when not in VR.
  80496. */
  80497. get: function () {
  80498. return this._deviceOrientationCamera;
  80499. },
  80500. enumerable: true,
  80501. configurable: true
  80502. });
  80503. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80504. /**
  80505. * Based on the current WebVR support, returns the current VR camera used.
  80506. */
  80507. get: function () {
  80508. if (this._webVRready) {
  80509. return this._webVRCamera;
  80510. }
  80511. else {
  80512. return this._scene.activeCamera;
  80513. }
  80514. },
  80515. enumerable: true,
  80516. configurable: true
  80517. });
  80518. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80519. /**
  80520. * The webVRCamera which is used when in VR.
  80521. */
  80522. get: function () {
  80523. return this._webVRCamera;
  80524. },
  80525. enumerable: true,
  80526. configurable: true
  80527. });
  80528. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80529. /**
  80530. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80531. */
  80532. get: function () {
  80533. return this._vrDeviceOrientationCamera;
  80534. },
  80535. enumerable: true,
  80536. configurable: true
  80537. });
  80538. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80539. get: function () {
  80540. var result = this._cameraGazer._teleportationRequestInitiated
  80541. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80542. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80543. return result;
  80544. },
  80545. enumerable: true,
  80546. configurable: true
  80547. });
  80548. // Raised when one of the controller has loaded successfully its associated default mesh
  80549. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80550. if (this.leftController && this.leftController.webVRController == webVRController) {
  80551. this._tryEnableInteractionOnController(this.leftController);
  80552. }
  80553. if (this.rightController && this.rightController.webVRController == webVRController) {
  80554. this._tryEnableInteractionOnController(this.rightController);
  80555. }
  80556. try {
  80557. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80558. }
  80559. catch (err) {
  80560. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80561. }
  80562. };
  80563. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80564. /**
  80565. * Gets a value indicating if we are currently in VR mode.
  80566. */
  80567. get: function () {
  80568. return this._webVRpresenting || this._fullscreenVRpresenting;
  80569. },
  80570. enumerable: true,
  80571. configurable: true
  80572. });
  80573. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80574. var vrDisplay = this._scene.getEngine().getVRDevice();
  80575. if (vrDisplay) {
  80576. var wasPresenting = this._webVRpresenting;
  80577. // A VR display is connected
  80578. this._webVRpresenting = vrDisplay.isPresenting;
  80579. if (wasPresenting && !this._webVRpresenting)
  80580. this.exitVR();
  80581. }
  80582. else {
  80583. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80584. }
  80585. this.updateButtonVisibility();
  80586. };
  80587. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80588. this._webVRsupported = eventArgs.vrSupported;
  80589. this._webVRready = !!eventArgs.vrDisplay;
  80590. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80591. this.updateButtonVisibility();
  80592. };
  80593. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80594. if (this._canvas && !this._useCustomVRButton) {
  80595. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80596. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80597. }
  80598. };
  80599. VRExperienceHelper.prototype.displayVRButton = function () {
  80600. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80601. document.body.appendChild(this._btnVR);
  80602. this._btnVRDisplayed = true;
  80603. }
  80604. };
  80605. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80606. if (!this._btnVR || this._useCustomVRButton) {
  80607. return;
  80608. }
  80609. this._btnVR.className = "babylonVRicon";
  80610. if (this.isInVRMode) {
  80611. this._btnVR.className += " vrdisplaypresenting";
  80612. }
  80613. else {
  80614. if (this._webVRready)
  80615. this._btnVR.className += " vrdisplayready";
  80616. if (this._webVRsupported)
  80617. this._btnVR.className += " vrdisplaysupported";
  80618. if (this._webVRrequesting)
  80619. this._btnVR.className += " vrdisplayrequesting";
  80620. }
  80621. };
  80622. /**
  80623. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80624. * Otherwise, will use the fullscreen API.
  80625. */
  80626. VRExperienceHelper.prototype.enterVR = function () {
  80627. if (this.onEnteringVRObservable) {
  80628. try {
  80629. this.onEnteringVRObservable.notifyObservers(this);
  80630. }
  80631. catch (err) {
  80632. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80633. }
  80634. }
  80635. if (this._scene.activeCamera) {
  80636. this._position = this._scene.activeCamera.position.clone();
  80637. // make sure that we return to the last active camera
  80638. this._existingCamera = this._scene.activeCamera;
  80639. }
  80640. if (this._webVRrequesting)
  80641. return;
  80642. // If WebVR is supported and a headset is connected
  80643. if (this._webVRready) {
  80644. if (!this._webVRpresenting) {
  80645. this._webVRCamera.position = this._position;
  80646. this._scene.activeCamera = this._webVRCamera;
  80647. }
  80648. }
  80649. else if (this._vrDeviceOrientationCamera) {
  80650. this._vrDeviceOrientationCamera.position = this._position;
  80651. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80652. this._scene.getEngine().switchFullscreen(true);
  80653. this.updateButtonVisibility();
  80654. }
  80655. if (this._scene.activeCamera && this._canvas) {
  80656. this._scene.activeCamera.attachControl(this._canvas);
  80657. }
  80658. if (this._interactionsEnabled) {
  80659. this._scene.registerBeforeRender(this.beforeRender);
  80660. }
  80661. };
  80662. /**
  80663. * Attempt to exit VR, or fullscreen.
  80664. */
  80665. VRExperienceHelper.prototype.exitVR = function () {
  80666. if (this.onExitingVRObservable) {
  80667. try {
  80668. this.onExitingVRObservable.notifyObservers(this);
  80669. }
  80670. catch (err) {
  80671. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80672. }
  80673. }
  80674. if (this._webVRpresenting) {
  80675. this._scene.getEngine().disableVR();
  80676. }
  80677. if (this._scene.activeCamera) {
  80678. this._position = this._scene.activeCamera.position.clone();
  80679. }
  80680. if (this._deviceOrientationCamera) {
  80681. this._deviceOrientationCamera.position = this._position;
  80682. this._scene.activeCamera = this._deviceOrientationCamera;
  80683. if (this._canvas) {
  80684. this._scene.activeCamera.attachControl(this._canvas);
  80685. }
  80686. }
  80687. else if (this._existingCamera) {
  80688. this._existingCamera.position = this._position;
  80689. this._scene.activeCamera = this._existingCamera;
  80690. }
  80691. this.updateButtonVisibility();
  80692. if (this._interactionsEnabled) {
  80693. this._scene.unregisterBeforeRender(this.beforeRender);
  80694. }
  80695. };
  80696. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80697. /**
  80698. * The position of the vr experience helper.
  80699. */
  80700. get: function () {
  80701. return this._position;
  80702. },
  80703. /**
  80704. * Sets the position of the vr experience helper.
  80705. */
  80706. set: function (value) {
  80707. this._position = value;
  80708. if (this._scene.activeCamera) {
  80709. this._scene.activeCamera.position = value;
  80710. }
  80711. },
  80712. enumerable: true,
  80713. configurable: true
  80714. });
  80715. /**
  80716. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80717. */
  80718. VRExperienceHelper.prototype.enableInteractions = function () {
  80719. var _this = this;
  80720. if (!this._interactionsEnabled) {
  80721. this._interactionsRequested = true;
  80722. if (this.leftController) {
  80723. this._enableInteractionOnController(this.leftController);
  80724. }
  80725. if (this.rightController) {
  80726. this._enableInteractionOnController(this.rightController);
  80727. }
  80728. this.raySelectionPredicate = function (mesh) {
  80729. return mesh.isVisible;
  80730. };
  80731. this.meshSelectionPredicate = function (mesh) {
  80732. return true;
  80733. };
  80734. this._raySelectionPredicate = function (mesh) {
  80735. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80736. && mesh.name.indexOf("teleportationTarget") === -1
  80737. && mesh.name.indexOf("torusTeleportation") === -1
  80738. && mesh.name.indexOf("laserPointer") === -1)) {
  80739. return _this.raySelectionPredicate(mesh);
  80740. }
  80741. return false;
  80742. };
  80743. this._interactionsEnabled = true;
  80744. }
  80745. };
  80746. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80747. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80748. if (this._floorMeshesCollection[i].id === mesh.id) {
  80749. return true;
  80750. }
  80751. }
  80752. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80753. return true;
  80754. }
  80755. return false;
  80756. };
  80757. /**
  80758. * Adds a floor mesh to be used for teleportation.
  80759. * @param floorMesh the mesh to be used for teleportation.
  80760. */
  80761. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80762. if (!this._floorMeshesCollection) {
  80763. return;
  80764. }
  80765. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80766. return;
  80767. }
  80768. this._floorMeshesCollection.push(floorMesh);
  80769. };
  80770. /**
  80771. * Removes a floor mesh from being used for teleportation.
  80772. * @param floorMesh the mesh to be removed.
  80773. */
  80774. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80775. if (!this._floorMeshesCollection) {
  80776. return;
  80777. }
  80778. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80779. if (meshIndex !== -1) {
  80780. this._floorMeshesCollection.splice(meshIndex, 1);
  80781. }
  80782. };
  80783. /**
  80784. * Enables interactions and teleportation using the VR controllers and gaze.
  80785. * @param vrTeleportationOptions options to modify teleportation behavior.
  80786. */
  80787. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80788. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80789. if (!this._teleportationInitialized) {
  80790. this._teleportationRequested = true;
  80791. this.enableInteractions();
  80792. if (vrTeleportationOptions.floorMeshName) {
  80793. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80794. }
  80795. if (vrTeleportationOptions.floorMeshes) {
  80796. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80797. }
  80798. if (this.leftController != null) {
  80799. this._enableTeleportationOnController(this.leftController);
  80800. }
  80801. if (this.rightController != null) {
  80802. this._enableTeleportationOnController(this.rightController);
  80803. }
  80804. // Creates an image processing post process for the vignette not relying
  80805. // on the main scene configuration for image processing to reduce setup and spaces
  80806. // (gamma/linear) conflicts.
  80807. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80808. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80809. imageProcessingConfiguration.vignetteEnabled = true;
  80810. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80811. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80812. this._teleportationInitialized = true;
  80813. if (this._isDefaultTeleportationTarget) {
  80814. this._createTeleportationCircles();
  80815. }
  80816. }
  80817. };
  80818. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  80819. var _this = this;
  80820. var controllerMesh = controller.webVRController.mesh;
  80821. if (controllerMesh) {
  80822. var makeNotPick = function (root) {
  80823. root.name += " laserPointer";
  80824. root.getChildMeshes().forEach(function (c) {
  80825. makeNotPick(c);
  80826. });
  80827. };
  80828. makeNotPick(controllerMesh);
  80829. var childMeshes = controllerMesh.getChildMeshes();
  80830. for (var i = 0; i < childMeshes.length; i++) {
  80831. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80832. controllerMesh = childMeshes[i];
  80833. break;
  80834. }
  80835. }
  80836. controller._setLaserPointerParent(controllerMesh);
  80837. controller._interactionsEnabled = true;
  80838. controller._activatePointer();
  80839. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80840. // Enabling / disabling laserPointer
  80841. if (_this._displayLaserPointer && stateObject.value === 1) {
  80842. if (controller._activePointer) {
  80843. controller._deactivatePointer();
  80844. }
  80845. else {
  80846. controller._activatePointer();
  80847. }
  80848. if (_this.displayGaze) {
  80849. controller._gazeTracker.isVisible = controller._activePointer;
  80850. }
  80851. }
  80852. });
  80853. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80854. if (!controller._pointerDownOnMeshAsked) {
  80855. if (stateObject.value > _this._padSensibilityUp) {
  80856. controller._selectionPointerDown();
  80857. }
  80858. }
  80859. else if (stateObject.value < _this._padSensibilityDown) {
  80860. controller._selectionPointerUp();
  80861. }
  80862. });
  80863. }
  80864. };
  80865. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  80866. // Dont teleport if another gaze already requested teleportation
  80867. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  80868. return;
  80869. }
  80870. if (!gazer._teleportationRequestInitiated) {
  80871. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  80872. gazer._activatePointer();
  80873. gazer._teleportationRequestInitiated = true;
  80874. }
  80875. }
  80876. else {
  80877. // Listening to the proper controller values changes to confirm teleportation
  80878. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80879. if (this._teleportActive) {
  80880. this._teleportCamera(this._haloCenter);
  80881. }
  80882. gazer._teleportationRequestInitiated = false;
  80883. }
  80884. }
  80885. };
  80886. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  80887. // Only rotate when user is not currently selecting a teleportation location
  80888. if (gazer._teleportationRequestInitiated) {
  80889. return;
  80890. }
  80891. if (!this._rotationLeftAsked) {
  80892. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  80893. this._rotationLeftAsked = true;
  80894. if (this._rotationAllowed) {
  80895. this._rotateCamera(false);
  80896. }
  80897. }
  80898. }
  80899. else {
  80900. if (stateObject.x > -this._padSensibilityDown) {
  80901. this._rotationLeftAsked = false;
  80902. }
  80903. }
  80904. if (!this._rotationRightAsked) {
  80905. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  80906. this._rotationRightAsked = true;
  80907. if (this._rotationAllowed) {
  80908. this._rotateCamera(true);
  80909. }
  80910. }
  80911. }
  80912. else {
  80913. if (stateObject.x < this._padSensibilityDown) {
  80914. this._rotationRightAsked = false;
  80915. }
  80916. }
  80917. };
  80918. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  80919. // Only teleport backwards when user is not currently selecting a teleportation location
  80920. if (gazer._teleportationRequestInitiated) {
  80921. return;
  80922. }
  80923. // Teleport backwards
  80924. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  80925. if (!gazer._teleportationBackRequestInitiated) {
  80926. if (!this.currentVRCamera) {
  80927. return;
  80928. }
  80929. // Get rotation and position of the current camera
  80930. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80931. var position = this.currentVRCamera.position;
  80932. // If the camera has device position, use that instead
  80933. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80934. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80935. position = this.currentVRCamera.devicePosition;
  80936. }
  80937. // Get matrix with only the y rotation of the device rotation
  80938. rotation.toEulerAnglesToRef(this._workingVector);
  80939. this._workingVector.z = 0;
  80940. this._workingVector.x = 0;
  80941. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80942. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80943. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80944. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80945. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80946. var ray = new BABYLON.Ray(position, this._workingVector);
  80947. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80948. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80949. this._teleportCamera(hit.pickedPoint);
  80950. }
  80951. gazer._teleportationBackRequestInitiated = true;
  80952. }
  80953. }
  80954. else {
  80955. gazer._teleportationBackRequestInitiated = false;
  80956. }
  80957. };
  80958. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  80959. var _this = this;
  80960. var controllerMesh = controller.webVRController.mesh;
  80961. if (controllerMesh) {
  80962. if (!controller._interactionsEnabled) {
  80963. this._enableInteractionOnController(controller);
  80964. }
  80965. controller._interactionsEnabled = true;
  80966. controller._teleportationEnabled = true;
  80967. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80968. controller._dpadPressed = false;
  80969. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80970. controller._dpadPressed = stateObject.pressed;
  80971. if (!controller._dpadPressed) {
  80972. _this._rotationLeftAsked = false;
  80973. _this._rotationRightAsked = false;
  80974. controller._teleportationBackRequestInitiated = false;
  80975. }
  80976. });
  80977. }
  80978. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80979. if (_this.teleportationEnabled) {
  80980. _this._checkTeleportBackwards(stateObject, controller);
  80981. _this._checkTeleportWithRay(stateObject, controller);
  80982. }
  80983. _this._checkRotate(stateObject, controller);
  80984. });
  80985. }
  80986. };
  80987. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80988. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80989. this._teleportationTarget.isPickable = false;
  80990. var length = 512;
  80991. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80992. dynamicTexture.hasAlpha = true;
  80993. var context = dynamicTexture.getContext();
  80994. var centerX = length / 2;
  80995. var centerY = length / 2;
  80996. var radius = 200;
  80997. context.beginPath();
  80998. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80999. context.fillStyle = this._teleportationFillColor;
  81000. context.fill();
  81001. context.lineWidth = 10;
  81002. context.strokeStyle = this._teleportationBorderColor;
  81003. context.stroke();
  81004. context.closePath();
  81005. dynamicTexture.update();
  81006. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81007. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81008. this._teleportationTarget.material = teleportationCircleMaterial;
  81009. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81010. torus.isPickable = false;
  81011. torus.parent = this._teleportationTarget;
  81012. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81013. var keys = [];
  81014. keys.push({
  81015. frame: 0,
  81016. value: 0
  81017. });
  81018. keys.push({
  81019. frame: 30,
  81020. value: 0.4
  81021. });
  81022. keys.push({
  81023. frame: 60,
  81024. value: 0
  81025. });
  81026. animationInnerCircle.setKeys(keys);
  81027. var easingFunction = new BABYLON.SineEase();
  81028. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81029. animationInnerCircle.setEasingFunction(easingFunction);
  81030. torus.animations = [];
  81031. torus.animations.push(animationInnerCircle);
  81032. this._scene.beginAnimation(torus, 0, 60, true);
  81033. this._hideTeleportationTarget();
  81034. };
  81035. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81036. this._teleportActive = true;
  81037. if (this._teleportationInitialized) {
  81038. this._teleportationTarget.isVisible = true;
  81039. if (this._isDefaultTeleportationTarget) {
  81040. this._teleportationTarget.getChildren()[0].isVisible = true;
  81041. }
  81042. }
  81043. };
  81044. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81045. this._teleportActive = false;
  81046. if (this._teleportationInitialized) {
  81047. this._teleportationTarget.isVisible = false;
  81048. if (this._isDefaultTeleportationTarget) {
  81049. this._teleportationTarget.getChildren()[0].isVisible = false;
  81050. }
  81051. }
  81052. };
  81053. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81054. var _this = this;
  81055. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81056. return;
  81057. }
  81058. if (right) {
  81059. this._rotationAngle++;
  81060. }
  81061. else {
  81062. this._rotationAngle--;
  81063. }
  81064. this.currentVRCamera.animations = [];
  81065. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81066. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81067. var animationRotationKeys = [];
  81068. animationRotationKeys.push({
  81069. frame: 0,
  81070. value: this.currentVRCamera.rotationQuaternion
  81071. });
  81072. animationRotationKeys.push({
  81073. frame: 6,
  81074. value: target
  81075. });
  81076. animationRotation.setKeys(animationRotationKeys);
  81077. animationRotation.setEasingFunction(this._circleEase);
  81078. this.currentVRCamera.animations.push(animationRotation);
  81079. this._postProcessMove.animations = [];
  81080. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81081. var vignetteWeightKeys = [];
  81082. vignetteWeightKeys.push({
  81083. frame: 0,
  81084. value: 0
  81085. });
  81086. vignetteWeightKeys.push({
  81087. frame: 3,
  81088. value: 4
  81089. });
  81090. vignetteWeightKeys.push({
  81091. frame: 6,
  81092. value: 0
  81093. });
  81094. animationPP.setKeys(vignetteWeightKeys);
  81095. animationPP.setEasingFunction(this._circleEase);
  81096. this._postProcessMove.animations.push(animationPP);
  81097. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81098. var vignetteStretchKeys = [];
  81099. vignetteStretchKeys.push({
  81100. frame: 0,
  81101. value: 0
  81102. });
  81103. vignetteStretchKeys.push({
  81104. frame: 3,
  81105. value: 10
  81106. });
  81107. vignetteStretchKeys.push({
  81108. frame: 6,
  81109. value: 0
  81110. });
  81111. animationPP2.setKeys(vignetteStretchKeys);
  81112. animationPP2.setEasingFunction(this._circleEase);
  81113. this._postProcessMove.animations.push(animationPP2);
  81114. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81115. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81116. this._postProcessMove.samples = 4;
  81117. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81118. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81119. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81120. });
  81121. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81122. };
  81123. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81124. if (hit.pickedPoint) {
  81125. if (gazer._teleportationRequestInitiated) {
  81126. this._displayTeleportationTarget();
  81127. this._haloCenter.copyFrom(hit.pickedPoint);
  81128. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81129. }
  81130. var pickNormal = hit.getNormal(true, false);
  81131. if (pickNormal) {
  81132. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81133. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81134. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81135. }
  81136. this._teleportationTarget.position.y += 0.1;
  81137. }
  81138. };
  81139. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81140. var _this = this;
  81141. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81142. return;
  81143. }
  81144. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81145. // offset of the headset from the anchor.
  81146. if (this.webVRCamera.leftCamera) {
  81147. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81148. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81149. location.subtractToRef(this._workingVector, this._workingVector);
  81150. }
  81151. else {
  81152. this._workingVector.copyFrom(location);
  81153. }
  81154. // Add height to account for user's height offset
  81155. if (this.isInVRMode) {
  81156. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81157. }
  81158. else {
  81159. this._workingVector.y += this._defaultHeight;
  81160. }
  81161. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81162. // Create animation from the camera's position to the new location
  81163. this.currentVRCamera.animations = [];
  81164. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81165. var animationCameraTeleportationKeys = [{
  81166. frame: 0,
  81167. value: this.currentVRCamera.position
  81168. },
  81169. {
  81170. frame: 11,
  81171. value: this._workingVector
  81172. }
  81173. ];
  81174. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81175. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81176. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81177. this._postProcessMove.animations = [];
  81178. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81179. var vignetteWeightKeys = [];
  81180. vignetteWeightKeys.push({
  81181. frame: 0,
  81182. value: 0
  81183. });
  81184. vignetteWeightKeys.push({
  81185. frame: 5,
  81186. value: 8
  81187. });
  81188. vignetteWeightKeys.push({
  81189. frame: 11,
  81190. value: 0
  81191. });
  81192. animationPP.setKeys(vignetteWeightKeys);
  81193. this._postProcessMove.animations.push(animationPP);
  81194. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81195. var vignetteStretchKeys = [];
  81196. vignetteStretchKeys.push({
  81197. frame: 0,
  81198. value: 0
  81199. });
  81200. vignetteStretchKeys.push({
  81201. frame: 5,
  81202. value: 10
  81203. });
  81204. vignetteStretchKeys.push({
  81205. frame: 11,
  81206. value: 0
  81207. });
  81208. animationPP2.setKeys(vignetteStretchKeys);
  81209. this._postProcessMove.animations.push(animationPP2);
  81210. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81211. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81212. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81213. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81214. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81215. });
  81216. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81217. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81218. });
  81219. this._hideTeleportationTarget();
  81220. };
  81221. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81222. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81223. return;
  81224. }
  81225. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81226. // Moving the gazeTracker on the mesh face targetted
  81227. if (hit && hit.pickedPoint) {
  81228. if (this._displayGaze) {
  81229. var multiplier = 1;
  81230. gazer._gazeTracker.isVisible = true;
  81231. if (gazer._isActionableMesh) {
  81232. multiplier = 3;
  81233. }
  81234. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81235. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81236. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81237. var pickNormal = hit.getNormal();
  81238. // To avoid z-fighting
  81239. var deltaFighting = 0.002;
  81240. if (pickNormal) {
  81241. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81242. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81243. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81244. }
  81245. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81246. if (gazer._gazeTracker.position.x < 0) {
  81247. gazer._gazeTracker.position.x += deltaFighting;
  81248. }
  81249. else {
  81250. gazer._gazeTracker.position.x -= deltaFighting;
  81251. }
  81252. if (gazer._gazeTracker.position.y < 0) {
  81253. gazer._gazeTracker.position.y += deltaFighting;
  81254. }
  81255. else {
  81256. gazer._gazeTracker.position.y -= deltaFighting;
  81257. }
  81258. if (gazer._gazeTracker.position.z < 0) {
  81259. gazer._gazeTracker.position.z += deltaFighting;
  81260. }
  81261. else {
  81262. gazer._gazeTracker.position.z -= deltaFighting;
  81263. }
  81264. }
  81265. // Changing the size of the laser pointer based on the distance from the targetted point
  81266. gazer._updatePointerDistance(hit.distance);
  81267. }
  81268. else {
  81269. gazer._gazeTracker.isVisible = false;
  81270. }
  81271. if (hit && hit.pickedMesh) {
  81272. gazer._currentHit = hit;
  81273. if (gazer._pointerDownOnMeshAsked) {
  81274. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81275. }
  81276. // The object selected is the floor, we're in a teleportation scenario
  81277. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81278. // Moving the teleportation area to this targetted point
  81279. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81280. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81281. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81282. }
  81283. gazer._currentMeshSelected = null;
  81284. if (gazer._teleportationRequestInitiated) {
  81285. this._moveTeleportationSelectorTo(hit, gazer);
  81286. }
  81287. return;
  81288. }
  81289. // If not, we're in a selection scenario
  81290. //this._teleportationAllowed = false;
  81291. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81292. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81293. this.onNewMeshPicked.notifyObservers(hit);
  81294. gazer._currentMeshSelected = hit.pickedMesh;
  81295. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81296. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81297. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81298. gazer._isActionableMesh = true;
  81299. }
  81300. else {
  81301. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81302. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81303. gazer._isActionableMesh = false;
  81304. }
  81305. try {
  81306. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81307. }
  81308. catch (err) {
  81309. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81310. }
  81311. }
  81312. else {
  81313. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81314. gazer._currentMeshSelected = null;
  81315. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81316. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81317. }
  81318. }
  81319. }
  81320. else {
  81321. gazer._currentHit = null;
  81322. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81323. gazer._currentMeshSelected = null;
  81324. //this._teleportationAllowed = false;
  81325. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81326. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81327. }
  81328. };
  81329. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81330. if (mesh) {
  81331. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81332. }
  81333. };
  81334. /**
  81335. * Sets the color of the laser ray from the vr controllers.
  81336. * @param color new color for the ray.
  81337. */
  81338. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81339. if (this.leftController) {
  81340. this.leftController._setLaserPointerColor(color);
  81341. }
  81342. if (this.rightController) {
  81343. this.rightController._setLaserPointerColor(color);
  81344. }
  81345. };
  81346. /**
  81347. * Sets the color of the ray from the vr headsets gaze.
  81348. * @param color new color for the ray.
  81349. */
  81350. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81351. if (!this._cameraGazer._gazeTracker.material) {
  81352. return;
  81353. }
  81354. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81355. if (this.leftController) {
  81356. this.leftController._gazeTracker.material.emissiveColor = color;
  81357. }
  81358. if (this.rightController) {
  81359. this.rightController._gazeTracker.material.emissiveColor = color;
  81360. }
  81361. };
  81362. /**
  81363. * Exits VR and disposes of the vr experience helper
  81364. */
  81365. VRExperienceHelper.prototype.dispose = function () {
  81366. if (this.isInVRMode) {
  81367. this.exitVR();
  81368. }
  81369. if (this._postProcessMove) {
  81370. this._postProcessMove.dispose();
  81371. }
  81372. if (this._webVRCamera) {
  81373. this._webVRCamera.dispose();
  81374. }
  81375. if (this._vrDeviceOrientationCamera) {
  81376. this._vrDeviceOrientationCamera.dispose();
  81377. }
  81378. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81379. document.body.removeChild(this._btnVR);
  81380. }
  81381. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81382. this._deviceOrientationCamera.dispose();
  81383. }
  81384. if (this._cameraGazer) {
  81385. this._cameraGazer.dispose();
  81386. }
  81387. if (this.leftController) {
  81388. this.leftController.dispose();
  81389. }
  81390. if (this.rightController) {
  81391. this.rightController.dispose();
  81392. }
  81393. if (this._teleportationTarget) {
  81394. this._teleportationTarget.dispose();
  81395. }
  81396. this._floorMeshesCollection = [];
  81397. document.removeEventListener("keydown", this._onKeyDown);
  81398. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81399. window.removeEventListener("resize", this._onResize);
  81400. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81401. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81402. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81403. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81404. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81405. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81406. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81407. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81408. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81409. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81410. this._scene.unregisterBeforeRender(this.beforeRender);
  81411. };
  81412. /**
  81413. * Gets the name of the VRExperienceHelper class
  81414. * @returns "VRExperienceHelper"
  81415. */
  81416. VRExperienceHelper.prototype.getClassName = function () {
  81417. return "VRExperienceHelper";
  81418. };
  81419. return VRExperienceHelper;
  81420. }());
  81421. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81422. })(BABYLON || (BABYLON = {}));
  81423. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81424. // Mainly based on these 2 articles :
  81425. // 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
  81426. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81427. var BABYLON;
  81428. (function (BABYLON) {
  81429. var JoystickAxis;
  81430. (function (JoystickAxis) {
  81431. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81432. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81433. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81434. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81435. var VirtualJoystick = /** @class */ (function () {
  81436. function VirtualJoystick(leftJoystick) {
  81437. var _this = this;
  81438. if (leftJoystick) {
  81439. this._leftJoystick = true;
  81440. }
  81441. else {
  81442. this._leftJoystick = false;
  81443. }
  81444. VirtualJoystick._globalJoystickIndex++;
  81445. // By default left & right arrow keys are moving the X
  81446. // and up & down keys are moving the Y
  81447. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81449. this.reverseLeftRight = false;
  81450. this.reverseUpDown = false;
  81451. // collections of pointers
  81452. this._touches = new BABYLON.StringDictionary();
  81453. this.deltaPosition = BABYLON.Vector3.Zero();
  81454. this._joystickSensibility = 25;
  81455. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81456. this._onResize = function (evt) {
  81457. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81458. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81459. if (VirtualJoystick.vjCanvas) {
  81460. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81461. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81462. }
  81463. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81464. };
  81465. // injecting a canvas element on top of the canvas 3D game
  81466. if (!VirtualJoystick.vjCanvas) {
  81467. window.addEventListener("resize", this._onResize, false);
  81468. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81469. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81470. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81471. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81472. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81473. VirtualJoystick.vjCanvas.style.width = "100%";
  81474. VirtualJoystick.vjCanvas.style.height = "100%";
  81475. VirtualJoystick.vjCanvas.style.position = "absolute";
  81476. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81477. VirtualJoystick.vjCanvas.style.top = "0px";
  81478. VirtualJoystick.vjCanvas.style.left = "0px";
  81479. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81480. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81481. // Support for jQuery PEP polyfill
  81482. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81483. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81484. if (!context) {
  81485. throw new Error("Unable to create canvas for virtual joystick");
  81486. }
  81487. VirtualJoystick.vjCanvasContext = context;
  81488. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81489. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81490. document.body.appendChild(VirtualJoystick.vjCanvas);
  81491. }
  81492. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81493. this.pressed = false;
  81494. // default joystick color
  81495. this._joystickColor = "cyan";
  81496. this._joystickPointerID = -1;
  81497. // current joystick position
  81498. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81499. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81500. // origin joystick position
  81501. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81502. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81503. this._onPointerDownHandlerRef = function (evt) {
  81504. _this._onPointerDown(evt);
  81505. };
  81506. this._onPointerMoveHandlerRef = function (evt) {
  81507. _this._onPointerMove(evt);
  81508. };
  81509. this._onPointerUpHandlerRef = function (evt) {
  81510. _this._onPointerUp(evt);
  81511. };
  81512. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81513. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81514. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81515. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81516. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81517. evt.preventDefault(); // Disables system menu
  81518. }, false);
  81519. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81520. }
  81521. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81522. this._joystickSensibility = newJoystickSensibility;
  81523. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81524. };
  81525. VirtualJoystick.prototype._onPointerDown = function (e) {
  81526. var positionOnScreenCondition;
  81527. e.preventDefault();
  81528. if (this._leftJoystick === true) {
  81529. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81530. }
  81531. else {
  81532. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81533. }
  81534. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81535. // First contact will be dedicated to the virtual joystick
  81536. this._joystickPointerID = e.pointerId;
  81537. this._joystickPointerStartPos.x = e.clientX;
  81538. this._joystickPointerStartPos.y = e.clientY;
  81539. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81540. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81541. this._deltaJoystickVector.x = 0;
  81542. this._deltaJoystickVector.y = 0;
  81543. this.pressed = true;
  81544. this._touches.add(e.pointerId.toString(), e);
  81545. }
  81546. else {
  81547. // You can only trigger the action buttons with a joystick declared
  81548. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81549. this._action();
  81550. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81551. }
  81552. }
  81553. };
  81554. VirtualJoystick.prototype._onPointerMove = function (e) {
  81555. // If the current pointer is the one associated to the joystick (first touch contact)
  81556. if (this._joystickPointerID == e.pointerId) {
  81557. this._joystickPointerPos.x = e.clientX;
  81558. this._joystickPointerPos.y = e.clientY;
  81559. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81560. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81561. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81562. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81563. switch (this._axisTargetedByLeftAndRight) {
  81564. case JoystickAxis.X:
  81565. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81566. break;
  81567. case JoystickAxis.Y:
  81568. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81569. break;
  81570. case JoystickAxis.Z:
  81571. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81572. break;
  81573. }
  81574. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81575. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81576. switch (this._axisTargetedByUpAndDown) {
  81577. case JoystickAxis.X:
  81578. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81579. break;
  81580. case JoystickAxis.Y:
  81581. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81582. break;
  81583. case JoystickAxis.Z:
  81584. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81585. break;
  81586. }
  81587. }
  81588. else {
  81589. var data = this._touches.get(e.pointerId.toString());
  81590. if (data) {
  81591. data.x = e.clientX;
  81592. data.y = e.clientY;
  81593. }
  81594. }
  81595. };
  81596. VirtualJoystick.prototype._onPointerUp = function (e) {
  81597. if (this._joystickPointerID == e.pointerId) {
  81598. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81599. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81600. this._joystickPointerID = -1;
  81601. this.pressed = false;
  81602. }
  81603. else {
  81604. var touch = this._touches.get(e.pointerId.toString());
  81605. if (touch) {
  81606. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81607. }
  81608. }
  81609. this._deltaJoystickVector.x = 0;
  81610. this._deltaJoystickVector.y = 0;
  81611. this._touches.remove(e.pointerId.toString());
  81612. };
  81613. /**
  81614. * Change the color of the virtual joystick
  81615. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81616. */
  81617. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81618. this._joystickColor = newColor;
  81619. };
  81620. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81621. this._action = action;
  81622. };
  81623. // Define which axis you'd like to control for left & right
  81624. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81625. switch (axis) {
  81626. case JoystickAxis.X:
  81627. case JoystickAxis.Y:
  81628. case JoystickAxis.Z:
  81629. this._axisTargetedByLeftAndRight = axis;
  81630. break;
  81631. default:
  81632. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81633. break;
  81634. }
  81635. };
  81636. // Define which axis you'd like to control for up & down
  81637. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81638. switch (axis) {
  81639. case JoystickAxis.X:
  81640. case JoystickAxis.Y:
  81641. case JoystickAxis.Z:
  81642. this._axisTargetedByUpAndDown = axis;
  81643. break;
  81644. default:
  81645. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81646. break;
  81647. }
  81648. };
  81649. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81650. var _this = this;
  81651. if (this.pressed) {
  81652. this._touches.forEach(function (key, touch) {
  81653. if (touch.pointerId === _this._joystickPointerID) {
  81654. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81655. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81656. VirtualJoystick.vjCanvasContext.beginPath();
  81657. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81658. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81659. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81660. VirtualJoystick.vjCanvasContext.stroke();
  81661. VirtualJoystick.vjCanvasContext.closePath();
  81662. VirtualJoystick.vjCanvasContext.beginPath();
  81663. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81664. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81665. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81666. VirtualJoystick.vjCanvasContext.stroke();
  81667. VirtualJoystick.vjCanvasContext.closePath();
  81668. VirtualJoystick.vjCanvasContext.beginPath();
  81669. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81670. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81671. VirtualJoystick.vjCanvasContext.stroke();
  81672. VirtualJoystick.vjCanvasContext.closePath();
  81673. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81674. }
  81675. else {
  81676. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81677. VirtualJoystick.vjCanvasContext.beginPath();
  81678. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81679. VirtualJoystick.vjCanvasContext.beginPath();
  81680. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81681. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81682. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81683. VirtualJoystick.vjCanvasContext.stroke();
  81684. VirtualJoystick.vjCanvasContext.closePath();
  81685. touch.prevX = touch.x;
  81686. touch.prevY = touch.y;
  81687. }
  81688. ;
  81689. });
  81690. }
  81691. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81692. };
  81693. VirtualJoystick.prototype.releaseCanvas = function () {
  81694. if (VirtualJoystick.vjCanvas) {
  81695. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81696. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81697. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81698. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81699. window.removeEventListener("resize", this._onResize);
  81700. document.body.removeChild(VirtualJoystick.vjCanvas);
  81701. VirtualJoystick.vjCanvas = null;
  81702. }
  81703. };
  81704. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81705. VirtualJoystick._globalJoystickIndex = 0;
  81706. return VirtualJoystick;
  81707. }());
  81708. BABYLON.VirtualJoystick = VirtualJoystick;
  81709. })(BABYLON || (BABYLON = {}));
  81710. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81711. var BABYLON;
  81712. (function (BABYLON) {
  81713. // We're mainly based on the logic defined into the FreeCamera code
  81714. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81715. __extends(VirtualJoysticksCamera, _super);
  81716. function VirtualJoysticksCamera(name, position, scene) {
  81717. var _this = _super.call(this, name, position, scene) || this;
  81718. _this.inputs.addVirtualJoystick();
  81719. return _this;
  81720. }
  81721. VirtualJoysticksCamera.prototype.getClassName = function () {
  81722. return "VirtualJoysticksCamera";
  81723. };
  81724. return VirtualJoysticksCamera;
  81725. }(BABYLON.FreeCamera));
  81726. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81727. })(BABYLON || (BABYLON = {}));
  81728. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81729. var BABYLON;
  81730. (function (BABYLON) {
  81731. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81732. function FreeCameraVirtualJoystickInput() {
  81733. }
  81734. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81735. return this._leftjoystick;
  81736. };
  81737. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81738. return this._rightjoystick;
  81739. };
  81740. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81741. if (this._leftjoystick) {
  81742. var camera = this.camera;
  81743. var speed = camera._computeLocalCameraSpeed() * 50;
  81744. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81745. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81746. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81747. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81748. if (!this._leftjoystick.pressed) {
  81749. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81750. }
  81751. if (!this._rightjoystick.pressed) {
  81752. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81753. }
  81754. }
  81755. };
  81756. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81757. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81758. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81759. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81760. this._leftjoystick.setJoystickSensibility(0.15);
  81761. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81762. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81763. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81764. this._rightjoystick.reverseUpDown = true;
  81765. this._rightjoystick.setJoystickSensibility(0.05);
  81766. this._rightjoystick.setJoystickColor("yellow");
  81767. };
  81768. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81769. this._leftjoystick.releaseCanvas();
  81770. this._rightjoystick.releaseCanvas();
  81771. };
  81772. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81773. return "FreeCameraVirtualJoystickInput";
  81774. };
  81775. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81776. return "virtualJoystick";
  81777. };
  81778. return FreeCameraVirtualJoystickInput;
  81779. }());
  81780. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81781. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81782. })(BABYLON || (BABYLON = {}));
  81783. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81784. var BABYLON;
  81785. (function (BABYLON) {
  81786. var SimplificationSettings = /** @class */ (function () {
  81787. function SimplificationSettings(quality, distance, optimizeMesh) {
  81788. this.quality = quality;
  81789. this.distance = distance;
  81790. this.optimizeMesh = optimizeMesh;
  81791. }
  81792. return SimplificationSettings;
  81793. }());
  81794. BABYLON.SimplificationSettings = SimplificationSettings;
  81795. var SimplificationQueue = /** @class */ (function () {
  81796. function SimplificationQueue() {
  81797. this.running = false;
  81798. this._simplificationArray = [];
  81799. }
  81800. SimplificationQueue.prototype.addTask = function (task) {
  81801. this._simplificationArray.push(task);
  81802. };
  81803. SimplificationQueue.prototype.executeNext = function () {
  81804. var task = this._simplificationArray.pop();
  81805. if (task) {
  81806. this.running = true;
  81807. this.runSimplification(task);
  81808. }
  81809. else {
  81810. this.running = false;
  81811. }
  81812. };
  81813. SimplificationQueue.prototype.runSimplification = function (task) {
  81814. var _this = this;
  81815. if (task.parallelProcessing) {
  81816. //parallel simplifier
  81817. task.settings.forEach(function (setting) {
  81818. var simplifier = _this.getSimplifier(task);
  81819. simplifier.simplify(setting, function (newMesh) {
  81820. task.mesh.addLODLevel(setting.distance, newMesh);
  81821. newMesh.isVisible = true;
  81822. //check if it is the last
  81823. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81824. //all done, run the success callback.
  81825. task.successCallback();
  81826. }
  81827. _this.executeNext();
  81828. });
  81829. });
  81830. }
  81831. else {
  81832. //single simplifier.
  81833. var simplifier = this.getSimplifier(task);
  81834. var runDecimation = function (setting, callback) {
  81835. simplifier.simplify(setting, function (newMesh) {
  81836. task.mesh.addLODLevel(setting.distance, newMesh);
  81837. newMesh.isVisible = true;
  81838. //run the next quality level
  81839. callback();
  81840. });
  81841. };
  81842. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81843. runDecimation(task.settings[loop.index], function () {
  81844. loop.executeNext();
  81845. });
  81846. }, function () {
  81847. //execution ended, run the success callback.
  81848. if (task.successCallback) {
  81849. task.successCallback();
  81850. }
  81851. _this.executeNext();
  81852. });
  81853. }
  81854. };
  81855. SimplificationQueue.prototype.getSimplifier = function (task) {
  81856. switch (task.simplificationType) {
  81857. case SimplificationType.QUADRATIC:
  81858. default:
  81859. return new QuadraticErrorSimplification(task.mesh);
  81860. }
  81861. };
  81862. return SimplificationQueue;
  81863. }());
  81864. BABYLON.SimplificationQueue = SimplificationQueue;
  81865. /**
  81866. * The implemented types of simplification.
  81867. * At the moment only Quadratic Error Decimation is implemented.
  81868. */
  81869. var SimplificationType;
  81870. (function (SimplificationType) {
  81871. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81872. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81873. var DecimationTriangle = /** @class */ (function () {
  81874. function DecimationTriangle(vertices) {
  81875. this.vertices = vertices;
  81876. this.error = new Array(4);
  81877. this.deleted = false;
  81878. this.isDirty = false;
  81879. this.deletePending = false;
  81880. this.borderFactor = 0;
  81881. }
  81882. return DecimationTriangle;
  81883. }());
  81884. BABYLON.DecimationTriangle = DecimationTriangle;
  81885. var DecimationVertex = /** @class */ (function () {
  81886. function DecimationVertex(position, id) {
  81887. this.position = position;
  81888. this.id = id;
  81889. this.isBorder = true;
  81890. this.q = new QuadraticMatrix();
  81891. this.triangleCount = 0;
  81892. this.triangleStart = 0;
  81893. this.originalOffsets = [];
  81894. }
  81895. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81896. this.position.copyFrom(newPosition);
  81897. };
  81898. return DecimationVertex;
  81899. }());
  81900. BABYLON.DecimationVertex = DecimationVertex;
  81901. var QuadraticMatrix = /** @class */ (function () {
  81902. function QuadraticMatrix(data) {
  81903. this.data = new Array(10);
  81904. for (var i = 0; i < 10; ++i) {
  81905. if (data && data[i]) {
  81906. this.data[i] = data[i];
  81907. }
  81908. else {
  81909. this.data[i] = 0;
  81910. }
  81911. }
  81912. }
  81913. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81914. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81915. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81916. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81917. return det;
  81918. };
  81919. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81920. for (var i = 0; i < 10; ++i) {
  81921. this.data[i] += matrix.data[i];
  81922. }
  81923. };
  81924. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81925. for (var i = 0; i < 10; ++i) {
  81926. this.data[i] += data[i];
  81927. }
  81928. };
  81929. QuadraticMatrix.prototype.add = function (matrix) {
  81930. var m = new QuadraticMatrix();
  81931. for (var i = 0; i < 10; ++i) {
  81932. m.data[i] = this.data[i] + matrix.data[i];
  81933. }
  81934. return m;
  81935. };
  81936. QuadraticMatrix.FromData = function (a, b, c, d) {
  81937. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81938. };
  81939. //returning an array to avoid garbage collection
  81940. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81941. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81942. };
  81943. return QuadraticMatrix;
  81944. }());
  81945. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81946. var Reference = /** @class */ (function () {
  81947. function Reference(vertexId, triangleId) {
  81948. this.vertexId = vertexId;
  81949. this.triangleId = triangleId;
  81950. }
  81951. return Reference;
  81952. }());
  81953. BABYLON.Reference = Reference;
  81954. /**
  81955. * An implementation of the Quadratic Error simplification algorithm.
  81956. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81957. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81958. * @author RaananW
  81959. */
  81960. var QuadraticErrorSimplification = /** @class */ (function () {
  81961. function QuadraticErrorSimplification(_mesh) {
  81962. this._mesh = _mesh;
  81963. this.syncIterations = 5000;
  81964. this.aggressiveness = 7;
  81965. this.decimationIterations = 100;
  81966. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81967. }
  81968. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81969. var _this = this;
  81970. this.initDecimatedMesh();
  81971. //iterating through the submeshes array, one after the other.
  81972. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81973. _this.initWithMesh(loop.index, function () {
  81974. _this.runDecimation(settings, loop.index, function () {
  81975. loop.executeNext();
  81976. });
  81977. }, settings.optimizeMesh);
  81978. }, function () {
  81979. setTimeout(function () {
  81980. successCallback(_this._reconstructedMesh);
  81981. }, 0);
  81982. });
  81983. };
  81984. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81985. var _this = this;
  81986. var targetCount = ~~(this.triangles.length * settings.quality);
  81987. var deletedTriangles = 0;
  81988. var triangleCount = this.triangles.length;
  81989. var iterationFunction = function (iteration, callback) {
  81990. setTimeout(function () {
  81991. if (iteration % 5 === 0) {
  81992. _this.updateMesh(iteration === 0);
  81993. }
  81994. for (var i = 0; i < _this.triangles.length; ++i) {
  81995. _this.triangles[i].isDirty = false;
  81996. }
  81997. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81998. var trianglesIterator = function (i) {
  81999. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82000. var t = _this.triangles[tIdx];
  82001. if (!t)
  82002. return;
  82003. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82004. return;
  82005. }
  82006. for (var j = 0; j < 3; ++j) {
  82007. if (t.error[j] < threshold) {
  82008. var deleted0 = [];
  82009. var deleted1 = [];
  82010. var v0 = t.vertices[j];
  82011. var v1 = t.vertices[(j + 1) % 3];
  82012. if (v0.isBorder || v1.isBorder)
  82013. continue;
  82014. var p = BABYLON.Vector3.Zero();
  82015. var n = BABYLON.Vector3.Zero();
  82016. var uv = BABYLON.Vector2.Zero();
  82017. var color = new BABYLON.Color4(0, 0, 0, 1);
  82018. _this.calculateError(v0, v1, p, n, uv, color);
  82019. var delTr = new Array();
  82020. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82021. continue;
  82022. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82023. continue;
  82024. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82025. continue;
  82026. var uniqueArray = new Array();
  82027. delTr.forEach(function (deletedT) {
  82028. if (uniqueArray.indexOf(deletedT) === -1) {
  82029. deletedT.deletePending = true;
  82030. uniqueArray.push(deletedT);
  82031. }
  82032. });
  82033. if (uniqueArray.length % 2 !== 0) {
  82034. continue;
  82035. }
  82036. v0.q = v1.q.add(v0.q);
  82037. v0.updatePosition(p);
  82038. var tStart = _this.references.length;
  82039. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82040. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82041. var tCount = _this.references.length - tStart;
  82042. if (tCount <= v0.triangleCount) {
  82043. if (tCount) {
  82044. for (var c = 0; c < tCount; c++) {
  82045. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82046. }
  82047. }
  82048. }
  82049. else {
  82050. v0.triangleStart = tStart;
  82051. }
  82052. v0.triangleCount = tCount;
  82053. break;
  82054. }
  82055. }
  82056. };
  82057. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82058. }, 0);
  82059. };
  82060. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82061. if (triangleCount - deletedTriangles <= targetCount)
  82062. loop.breakLoop();
  82063. else {
  82064. iterationFunction(loop.index, function () {
  82065. loop.executeNext();
  82066. });
  82067. }
  82068. }, function () {
  82069. setTimeout(function () {
  82070. //reconstruct this part of the mesh
  82071. _this.reconstructMesh(submeshIndex);
  82072. successCallback();
  82073. }, 0);
  82074. });
  82075. };
  82076. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82077. var _this = this;
  82078. this.vertices = [];
  82079. this.triangles = [];
  82080. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82081. var indices = this._mesh.getIndices();
  82082. var submesh = this._mesh.subMeshes[submeshIndex];
  82083. var findInVertices = function (positionToSearch) {
  82084. if (optimizeMesh) {
  82085. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82086. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82087. return _this.vertices[ii];
  82088. }
  82089. }
  82090. }
  82091. return null;
  82092. };
  82093. var vertexReferences = [];
  82094. var vertexInit = function (i) {
  82095. if (!positionData) {
  82096. return;
  82097. }
  82098. var offset = i + submesh.verticesStart;
  82099. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82100. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82101. vertex.originalOffsets.push(offset);
  82102. if (vertex.id === _this.vertices.length) {
  82103. _this.vertices.push(vertex);
  82104. }
  82105. vertexReferences.push(vertex.id);
  82106. };
  82107. //var totalVertices = mesh.getTotalVertices();
  82108. var totalVertices = submesh.verticesCount;
  82109. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82110. var indicesInit = function (i) {
  82111. if (!indices) {
  82112. return;
  82113. }
  82114. var offset = (submesh.indexStart / 3) + i;
  82115. var pos = (offset * 3);
  82116. var i0 = indices[pos + 0];
  82117. var i1 = indices[pos + 1];
  82118. var i2 = indices[pos + 2];
  82119. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82120. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82121. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82122. var triangle = new DecimationTriangle([v0, v1, v2]);
  82123. triangle.originalOffset = pos;
  82124. _this.triangles.push(triangle);
  82125. };
  82126. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82127. _this.init(callback);
  82128. });
  82129. });
  82130. };
  82131. QuadraticErrorSimplification.prototype.init = function (callback) {
  82132. var _this = this;
  82133. var triangleInit1 = function (i) {
  82134. var t = _this.triangles[i];
  82135. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82136. for (var j = 0; j < 3; j++) {
  82137. 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))));
  82138. }
  82139. };
  82140. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82141. var triangleInit2 = function (i) {
  82142. var t = _this.triangles[i];
  82143. for (var j = 0; j < 3; ++j) {
  82144. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82145. }
  82146. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82147. };
  82148. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82149. callback();
  82150. });
  82151. });
  82152. };
  82153. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82154. var newTriangles = [];
  82155. var i;
  82156. for (i = 0; i < this.vertices.length; ++i) {
  82157. this.vertices[i].triangleCount = 0;
  82158. }
  82159. var t;
  82160. var j;
  82161. for (i = 0; i < this.triangles.length; ++i) {
  82162. if (!this.triangles[i].deleted) {
  82163. t = this.triangles[i];
  82164. for (j = 0; j < 3; ++j) {
  82165. t.vertices[j].triangleCount = 1;
  82166. }
  82167. newTriangles.push(t);
  82168. }
  82169. }
  82170. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82171. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82172. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82173. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82174. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82175. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82176. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82177. var vertexCount = 0;
  82178. for (i = 0; i < this.vertices.length; ++i) {
  82179. var vertex = this.vertices[i];
  82180. vertex.id = vertexCount;
  82181. if (vertex.triangleCount) {
  82182. vertex.originalOffsets.forEach(function (originalOffset) {
  82183. if (!normalData) {
  82184. return;
  82185. }
  82186. newPositionData.push(vertex.position.x);
  82187. newPositionData.push(vertex.position.y);
  82188. newPositionData.push(vertex.position.z);
  82189. newNormalData.push(normalData[originalOffset * 3]);
  82190. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82191. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82192. if (uvs && uvs.length) {
  82193. newUVsData.push(uvs[(originalOffset * 2)]);
  82194. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82195. }
  82196. else if (colorsData && colorsData.length) {
  82197. newColorsData.push(colorsData[(originalOffset * 4)]);
  82198. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82199. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82200. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82201. }
  82202. ++vertexCount;
  82203. });
  82204. }
  82205. }
  82206. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82207. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82208. var submeshesArray = this._reconstructedMesh.subMeshes;
  82209. this._reconstructedMesh.subMeshes = [];
  82210. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82211. var originalIndices = this._mesh.getIndices();
  82212. for (i = 0; i < newTriangles.length; ++i) {
  82213. t = newTriangles[i]; //now get the new referencing point for each vertex
  82214. [0, 1, 2].forEach(function (idx) {
  82215. var id = originalIndices[t.originalOffset + idx];
  82216. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82217. if (offset < 0)
  82218. offset = 0;
  82219. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82220. });
  82221. }
  82222. //overwriting the old vertex buffers and indices.
  82223. this._reconstructedMesh.setIndices(newIndicesArray);
  82224. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82225. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82226. if (newUVsData.length > 0)
  82227. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82228. if (newColorsData.length > 0)
  82229. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82230. //create submesh
  82231. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82232. if (submeshIndex > 0) {
  82233. this._reconstructedMesh.subMeshes = [];
  82234. submeshesArray.forEach(function (submesh) {
  82235. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82236. });
  82237. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82238. }
  82239. };
  82240. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82241. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82242. this._reconstructedMesh.material = this._mesh.material;
  82243. this._reconstructedMesh.parent = this._mesh.parent;
  82244. this._reconstructedMesh.isVisible = false;
  82245. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82246. };
  82247. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82248. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82249. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82250. if (t.deleted)
  82251. continue;
  82252. var s = this.references[vertex1.triangleStart + i].vertexId;
  82253. var v1 = t.vertices[(s + 1) % 3];
  82254. var v2 = t.vertices[(s + 2) % 3];
  82255. if ((v1 === vertex2 || v2 === vertex2)) {
  82256. deletedArray[i] = true;
  82257. delTr.push(t);
  82258. continue;
  82259. }
  82260. var d1 = v1.position.subtract(point);
  82261. d1 = d1.normalize();
  82262. var d2 = v2.position.subtract(point);
  82263. d2 = d2.normalize();
  82264. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82265. return true;
  82266. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82267. deletedArray[i] = false;
  82268. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82269. return true;
  82270. }
  82271. return false;
  82272. };
  82273. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82274. var newDeleted = deletedTriangles;
  82275. for (var i = 0; i < vertex.triangleCount; ++i) {
  82276. var ref = this.references[vertex.triangleStart + i];
  82277. var t = this.triangles[ref.triangleId];
  82278. if (t.deleted)
  82279. continue;
  82280. if (deletedArray[i] && t.deletePending) {
  82281. t.deleted = true;
  82282. newDeleted++;
  82283. continue;
  82284. }
  82285. t.vertices[ref.vertexId] = origVertex;
  82286. t.isDirty = true;
  82287. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82288. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82289. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82290. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82291. this.references.push(ref);
  82292. }
  82293. return newDeleted;
  82294. };
  82295. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82296. for (var i = 0; i < this.vertices.length; ++i) {
  82297. var vCount = [];
  82298. var vId = [];
  82299. var v = this.vertices[i];
  82300. var j;
  82301. for (j = 0; j < v.triangleCount; ++j) {
  82302. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82303. for (var ii = 0; ii < 3; ii++) {
  82304. var ofs = 0;
  82305. var vv = triangle.vertices[ii];
  82306. while (ofs < vCount.length) {
  82307. if (vId[ofs] === vv.id)
  82308. break;
  82309. ++ofs;
  82310. }
  82311. if (ofs === vCount.length) {
  82312. vCount.push(1);
  82313. vId.push(vv.id);
  82314. }
  82315. else {
  82316. vCount[ofs]++;
  82317. }
  82318. }
  82319. }
  82320. for (j = 0; j < vCount.length; ++j) {
  82321. if (vCount[j] === 1) {
  82322. this.vertices[vId[j]].isBorder = true;
  82323. }
  82324. else {
  82325. this.vertices[vId[j]].isBorder = false;
  82326. }
  82327. }
  82328. }
  82329. };
  82330. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82331. if (identifyBorders === void 0) { identifyBorders = false; }
  82332. var i;
  82333. if (!identifyBorders) {
  82334. var newTrianglesVector = [];
  82335. for (i = 0; i < this.triangles.length; ++i) {
  82336. if (!this.triangles[i].deleted) {
  82337. newTrianglesVector.push(this.triangles[i]);
  82338. }
  82339. }
  82340. this.triangles = newTrianglesVector;
  82341. }
  82342. for (i = 0; i < this.vertices.length; ++i) {
  82343. this.vertices[i].triangleCount = 0;
  82344. this.vertices[i].triangleStart = 0;
  82345. }
  82346. var t;
  82347. var j;
  82348. var v;
  82349. for (i = 0; i < this.triangles.length; ++i) {
  82350. t = this.triangles[i];
  82351. for (j = 0; j < 3; ++j) {
  82352. v = t.vertices[j];
  82353. v.triangleCount++;
  82354. }
  82355. }
  82356. var tStart = 0;
  82357. for (i = 0; i < this.vertices.length; ++i) {
  82358. this.vertices[i].triangleStart = tStart;
  82359. tStart += this.vertices[i].triangleCount;
  82360. this.vertices[i].triangleCount = 0;
  82361. }
  82362. var newReferences = new Array(this.triangles.length * 3);
  82363. for (i = 0; i < this.triangles.length; ++i) {
  82364. t = this.triangles[i];
  82365. for (j = 0; j < 3; ++j) {
  82366. v = t.vertices[j];
  82367. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82368. v.triangleCount++;
  82369. }
  82370. }
  82371. this.references = newReferences;
  82372. if (identifyBorders) {
  82373. this.identifyBorder();
  82374. }
  82375. };
  82376. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82377. var x = point.x;
  82378. var y = point.y;
  82379. var z = point.z;
  82380. 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
  82381. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82382. };
  82383. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82384. var q = vertex1.q.add(vertex2.q);
  82385. var border = vertex1.isBorder && vertex2.isBorder;
  82386. var error = 0;
  82387. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82388. if (qDet !== 0 && !border) {
  82389. if (!pointResult) {
  82390. pointResult = BABYLON.Vector3.Zero();
  82391. }
  82392. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82393. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82394. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82395. error = this.vertexError(q, pointResult);
  82396. }
  82397. else {
  82398. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82399. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82400. var error1 = this.vertexError(q, vertex1.position);
  82401. var error2 = this.vertexError(q, vertex2.position);
  82402. var error3 = this.vertexError(q, p3);
  82403. error = Math.min(error1, error2, error3);
  82404. if (error === error1) {
  82405. if (pointResult) {
  82406. pointResult.copyFrom(vertex1.position);
  82407. }
  82408. }
  82409. else if (error === error2) {
  82410. if (pointResult) {
  82411. pointResult.copyFrom(vertex2.position);
  82412. }
  82413. }
  82414. else {
  82415. if (pointResult) {
  82416. pointResult.copyFrom(p3);
  82417. }
  82418. }
  82419. }
  82420. return error;
  82421. };
  82422. return QuadraticErrorSimplification;
  82423. }());
  82424. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82425. })(BABYLON || (BABYLON = {}));
  82426. //# sourceMappingURL=babylon.meshSimplification.js.map
  82427. var BABYLON;
  82428. (function (BABYLON) {
  82429. var MeshLODLevel = /** @class */ (function () {
  82430. function MeshLODLevel(distance, mesh) {
  82431. this.distance = distance;
  82432. this.mesh = mesh;
  82433. }
  82434. return MeshLODLevel;
  82435. }());
  82436. BABYLON.MeshLODLevel = MeshLODLevel;
  82437. })(BABYLON || (BABYLON = {}));
  82438. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82439. var BABYLON;
  82440. (function (BABYLON) {
  82441. /**
  82442. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82443. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82444. */
  82445. var SceneOptimization = /** @class */ (function () {
  82446. /**
  82447. * Creates the SceneOptimization object
  82448. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82449. * @param desc defines the description associated with the optimization
  82450. */
  82451. function SceneOptimization(
  82452. /**
  82453. * Defines the priority of this optimization (0 by default which means first in the list)
  82454. */
  82455. priority) {
  82456. if (priority === void 0) { priority = 0; }
  82457. this.priority = priority;
  82458. }
  82459. /**
  82460. * Gets a string describing the action executed by the current optimization
  82461. * @returns description string
  82462. */
  82463. SceneOptimization.prototype.getDescription = function () {
  82464. return "";
  82465. };
  82466. /**
  82467. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82468. * @param scene defines the current scene where to apply this optimization
  82469. * @param optimizer defines the current optimizer
  82470. * @returns true if everything that can be done was applied
  82471. */
  82472. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82473. return true;
  82474. };
  82475. ;
  82476. return SceneOptimization;
  82477. }());
  82478. BABYLON.SceneOptimization = SceneOptimization;
  82479. /**
  82480. * Defines an optimization used to reduce the size of render target textures
  82481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82482. */
  82483. var TextureOptimization = /** @class */ (function (_super) {
  82484. __extends(TextureOptimization, _super);
  82485. /**
  82486. * Creates the TextureOptimization object
  82487. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82488. * @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
  82489. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82490. */
  82491. function TextureOptimization(
  82492. /**
  82493. * Defines the priority of this optimization (0 by default which means first in the list)
  82494. */
  82495. priority,
  82496. /**
  82497. * 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
  82498. */
  82499. maximumSize,
  82500. /**
  82501. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82502. */
  82503. step) {
  82504. if (priority === void 0) { priority = 0; }
  82505. if (maximumSize === void 0) { maximumSize = 1024; }
  82506. if (step === void 0) { step = 0.5; }
  82507. var _this = _super.call(this, priority) || this;
  82508. _this.priority = priority;
  82509. _this.maximumSize = maximumSize;
  82510. _this.step = step;
  82511. return _this;
  82512. }
  82513. /**
  82514. * Gets a string describing the action executed by the current optimization
  82515. * @returns description string
  82516. */
  82517. TextureOptimization.prototype.getDescription = function () {
  82518. return "Reducing render target texture size to " + this.maximumSize;
  82519. };
  82520. /**
  82521. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82522. * @param scene defines the current scene where to apply this optimization
  82523. * @param optimizer defines the current optimizer
  82524. * @returns true if everything that can be done was applied
  82525. */
  82526. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82527. var allDone = true;
  82528. for (var index = 0; index < scene.textures.length; index++) {
  82529. var texture = scene.textures[index];
  82530. if (!texture.canRescale || texture.getContext) {
  82531. continue;
  82532. }
  82533. var currentSize = texture.getSize();
  82534. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82535. if (maxDimension > this.maximumSize) {
  82536. texture.scale(this.step);
  82537. allDone = false;
  82538. }
  82539. }
  82540. return allDone;
  82541. };
  82542. return TextureOptimization;
  82543. }(SceneOptimization));
  82544. BABYLON.TextureOptimization = TextureOptimization;
  82545. /**
  82546. * Defines an optimization used to increase or decrease the rendering resolution
  82547. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82548. */
  82549. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82550. __extends(HardwareScalingOptimization, _super);
  82551. /**
  82552. * Creates the HardwareScalingOptimization object
  82553. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82554. * @param maximumScale defines the maximum scale to use (2 by default)
  82555. * @param step defines the step to use between two passes (0.5 by default)
  82556. */
  82557. function HardwareScalingOptimization(
  82558. /**
  82559. * Defines the priority of this optimization (0 by default which means first in the list)
  82560. */
  82561. priority,
  82562. /**
  82563. * Defines the maximum scale to use (2 by default)
  82564. */
  82565. maximumScale,
  82566. /**
  82567. * Defines the step to use between two passes (0.5 by default)
  82568. */
  82569. step) {
  82570. if (priority === void 0) { priority = 0; }
  82571. if (maximumScale === void 0) { maximumScale = 2; }
  82572. if (step === void 0) { step = 0.25; }
  82573. var _this = _super.call(this, priority) || this;
  82574. _this.priority = priority;
  82575. _this.maximumScale = maximumScale;
  82576. _this.step = step;
  82577. _this._currentScale = -1;
  82578. _this._directionOffset = 1;
  82579. return _this;
  82580. }
  82581. /**
  82582. * Gets a string describing the action executed by the current optimization
  82583. * @return description string
  82584. */
  82585. HardwareScalingOptimization.prototype.getDescription = function () {
  82586. return "Setting hardware scaling level to " + this._currentScale;
  82587. };
  82588. /**
  82589. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82590. * @param scene defines the current scene where to apply this optimization
  82591. * @param optimizer defines the current optimizer
  82592. * @returns true if everything that can be done was applied
  82593. */
  82594. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82595. if (this._currentScale === -1) {
  82596. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82597. if (this._currentScale > this.maximumScale) {
  82598. this._directionOffset = -1;
  82599. }
  82600. }
  82601. this._currentScale += this._directionOffset * this.step;
  82602. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82603. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82604. };
  82605. ;
  82606. return HardwareScalingOptimization;
  82607. }(SceneOptimization));
  82608. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82609. /**
  82610. * Defines an optimization used to remove shadows
  82611. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82612. */
  82613. var ShadowsOptimization = /** @class */ (function (_super) {
  82614. __extends(ShadowsOptimization, _super);
  82615. function ShadowsOptimization() {
  82616. return _super !== null && _super.apply(this, arguments) || this;
  82617. }
  82618. /**
  82619. * Gets a string describing the action executed by the current optimization
  82620. * @return description string
  82621. */
  82622. ShadowsOptimization.prototype.getDescription = function () {
  82623. return "Turning shadows on/off";
  82624. };
  82625. /**
  82626. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82627. * @param scene defines the current scene where to apply this optimization
  82628. * @param optimizer defines the current optimizer
  82629. * @returns true if everything that can be done was applied
  82630. */
  82631. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82632. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82633. return true;
  82634. };
  82635. ;
  82636. return ShadowsOptimization;
  82637. }(SceneOptimization));
  82638. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82639. /**
  82640. * Defines an optimization used to turn post-processes off
  82641. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82642. */
  82643. var PostProcessesOptimization = /** @class */ (function (_super) {
  82644. __extends(PostProcessesOptimization, _super);
  82645. function PostProcessesOptimization() {
  82646. return _super !== null && _super.apply(this, arguments) || this;
  82647. }
  82648. /**
  82649. * Gets a string describing the action executed by the current optimization
  82650. * @return description string
  82651. */
  82652. PostProcessesOptimization.prototype.getDescription = function () {
  82653. return "Turning post-processes on/off";
  82654. };
  82655. /**
  82656. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82657. * @param scene defines the current scene where to apply this optimization
  82658. * @param optimizer defines the current optimizer
  82659. * @returns true if everything that can be done was applied
  82660. */
  82661. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82662. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82663. return true;
  82664. };
  82665. ;
  82666. return PostProcessesOptimization;
  82667. }(SceneOptimization));
  82668. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82669. /**
  82670. * Defines an optimization used to turn lens flares off
  82671. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82672. */
  82673. var LensFlaresOptimization = /** @class */ (function (_super) {
  82674. __extends(LensFlaresOptimization, _super);
  82675. function LensFlaresOptimization() {
  82676. return _super !== null && _super.apply(this, arguments) || this;
  82677. }
  82678. /**
  82679. * Gets a string describing the action executed by the current optimization
  82680. * @return description string
  82681. */
  82682. LensFlaresOptimization.prototype.getDescription = function () {
  82683. return "Turning lens flares on/off";
  82684. };
  82685. /**
  82686. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82687. * @param scene defines the current scene where to apply this optimization
  82688. * @param optimizer defines the current optimizer
  82689. * @returns true if everything that can be done was applied
  82690. */
  82691. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82692. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82693. return true;
  82694. };
  82695. ;
  82696. return LensFlaresOptimization;
  82697. }(SceneOptimization));
  82698. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82699. /**
  82700. * Defines an optimization based on user defined callback.
  82701. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82702. */
  82703. var CustomOptimization = /** @class */ (function (_super) {
  82704. __extends(CustomOptimization, _super);
  82705. function CustomOptimization() {
  82706. return _super !== null && _super.apply(this, arguments) || this;
  82707. }
  82708. /**
  82709. * Gets a string describing the action executed by the current optimization
  82710. * @returns description string
  82711. */
  82712. CustomOptimization.prototype.getDescription = function () {
  82713. if (this.onGetDescription) {
  82714. return this.onGetDescription();
  82715. }
  82716. return "Running user defined callback";
  82717. };
  82718. /**
  82719. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82720. * @param scene defines the current scene where to apply this optimization
  82721. * @param optimizer defines the current optimizer
  82722. * @returns true if everything that can be done was applied
  82723. */
  82724. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82725. if (this.onApply) {
  82726. return this.onApply(scene, optimizer);
  82727. }
  82728. return true;
  82729. };
  82730. ;
  82731. return CustomOptimization;
  82732. }(SceneOptimization));
  82733. BABYLON.CustomOptimization = CustomOptimization;
  82734. /**
  82735. * Defines an optimization used to turn particles off
  82736. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82737. */
  82738. var ParticlesOptimization = /** @class */ (function (_super) {
  82739. __extends(ParticlesOptimization, _super);
  82740. function ParticlesOptimization() {
  82741. return _super !== null && _super.apply(this, arguments) || this;
  82742. }
  82743. /**
  82744. * Gets a string describing the action executed by the current optimization
  82745. * @return description string
  82746. */
  82747. ParticlesOptimization.prototype.getDescription = function () {
  82748. return "Turning particles on/off";
  82749. };
  82750. /**
  82751. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82752. * @param scene defines the current scene where to apply this optimization
  82753. * @param optimizer defines the current optimizer
  82754. * @returns true if everything that can be done was applied
  82755. */
  82756. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82757. scene.particlesEnabled = optimizer.isInImprovementMode;
  82758. return true;
  82759. };
  82760. ;
  82761. return ParticlesOptimization;
  82762. }(SceneOptimization));
  82763. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82764. /**
  82765. * Defines an optimization used to turn render targets off
  82766. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82767. */
  82768. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82769. __extends(RenderTargetsOptimization, _super);
  82770. function RenderTargetsOptimization() {
  82771. return _super !== null && _super.apply(this, arguments) || this;
  82772. }
  82773. /**
  82774. * Gets a string describing the action executed by the current optimization
  82775. * @return description string
  82776. */
  82777. RenderTargetsOptimization.prototype.getDescription = function () {
  82778. return "Turning render targets off";
  82779. };
  82780. /**
  82781. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82782. * @param scene defines the current scene where to apply this optimization
  82783. * @param optimizer defines the current optimizer
  82784. * @returns true if everything that can be done was applied
  82785. */
  82786. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82787. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82788. return true;
  82789. };
  82790. ;
  82791. return RenderTargetsOptimization;
  82792. }(SceneOptimization));
  82793. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82794. /**
  82795. * Defines an optimization used to merge meshes with compatible materials
  82796. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82797. */
  82798. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82799. __extends(MergeMeshesOptimization, _super);
  82800. function MergeMeshesOptimization() {
  82801. var _this = _super !== null && _super.apply(this, arguments) || this;
  82802. _this._canBeMerged = function (abstractMesh) {
  82803. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82804. return false;
  82805. }
  82806. var mesh = abstractMesh;
  82807. if (!mesh.isVisible || !mesh.isEnabled()) {
  82808. return false;
  82809. }
  82810. if (mesh.instances.length > 0) {
  82811. return false;
  82812. }
  82813. if (mesh.skeleton || mesh.hasLODLevels) {
  82814. return false;
  82815. }
  82816. if (mesh.parent) {
  82817. return false;
  82818. }
  82819. return true;
  82820. };
  82821. return _this;
  82822. }
  82823. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82824. /**
  82825. * Gets or sets a boolean which defines if optimization octree has to be updated
  82826. */
  82827. get: function () {
  82828. return MergeMeshesOptimization._UpdateSelectionTree;
  82829. },
  82830. /**
  82831. * Gets or sets a boolean which defines if optimization octree has to be updated
  82832. */
  82833. set: function (value) {
  82834. MergeMeshesOptimization._UpdateSelectionTree = value;
  82835. },
  82836. enumerable: true,
  82837. configurable: true
  82838. });
  82839. /**
  82840. * Gets a string describing the action executed by the current optimization
  82841. * @return description string
  82842. */
  82843. MergeMeshesOptimization.prototype.getDescription = function () {
  82844. return "Merging similar meshes together";
  82845. };
  82846. /**
  82847. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82848. * @param scene defines the current scene where to apply this optimization
  82849. * @param optimizer defines the current optimizer
  82850. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82851. * @returns true if everything that can be done was applied
  82852. */
  82853. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82854. var globalPool = scene.meshes.slice(0);
  82855. var globalLength = globalPool.length;
  82856. for (var index = 0; index < globalLength; index++) {
  82857. var currentPool = new Array();
  82858. var current = globalPool[index];
  82859. // Checks
  82860. if (!this._canBeMerged(current)) {
  82861. continue;
  82862. }
  82863. currentPool.push(current);
  82864. // Find compatible meshes
  82865. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82866. var otherMesh = globalPool[subIndex];
  82867. if (!this._canBeMerged(otherMesh)) {
  82868. continue;
  82869. }
  82870. if (otherMesh.material !== current.material) {
  82871. continue;
  82872. }
  82873. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82874. continue;
  82875. }
  82876. currentPool.push(otherMesh);
  82877. globalLength--;
  82878. globalPool.splice(subIndex, 1);
  82879. subIndex--;
  82880. }
  82881. if (currentPool.length < 2) {
  82882. continue;
  82883. }
  82884. // Merge meshes
  82885. BABYLON.Mesh.MergeMeshes(currentPool);
  82886. }
  82887. if (updateSelectionTree != undefined) {
  82888. if (updateSelectionTree) {
  82889. scene.createOrUpdateSelectionOctree();
  82890. }
  82891. }
  82892. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82893. scene.createOrUpdateSelectionOctree();
  82894. }
  82895. return true;
  82896. };
  82897. ;
  82898. MergeMeshesOptimization._UpdateSelectionTree = false;
  82899. return MergeMeshesOptimization;
  82900. }(SceneOptimization));
  82901. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82902. /**
  82903. * Defines a list of options used by SceneOptimizer
  82904. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82905. */
  82906. var SceneOptimizerOptions = /** @class */ (function () {
  82907. /**
  82908. * Creates a new list of options used by SceneOptimizer
  82909. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82910. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82911. */
  82912. function SceneOptimizerOptions(
  82913. /**
  82914. * Defines the target frame rate to reach (60 by default)
  82915. */
  82916. targetFrameRate,
  82917. /**
  82918. * Defines the interval between two checkes (2000ms by default)
  82919. */
  82920. trackerDuration) {
  82921. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82922. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82923. this.targetFrameRate = targetFrameRate;
  82924. this.trackerDuration = trackerDuration;
  82925. /**
  82926. * Gets the list of optimizations to apply
  82927. */
  82928. this.optimizations = new Array();
  82929. }
  82930. /**
  82931. * Add a new optimization
  82932. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82933. * @returns the current SceneOptimizerOptions
  82934. */
  82935. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82936. this.optimizations.push(optimization);
  82937. return this;
  82938. };
  82939. /**
  82940. * Add a new custom optimization
  82941. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82942. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82943. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82944. * @returns the current SceneOptimizerOptions
  82945. */
  82946. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82947. if (priority === void 0) { priority = 0; }
  82948. var optimization = new CustomOptimization(priority);
  82949. optimization.onApply = onApply;
  82950. optimization.onGetDescription = onGetDescription;
  82951. this.optimizations.push(optimization);
  82952. return this;
  82953. };
  82954. /**
  82955. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82956. * @param targetFrameRate defines the target frame rate (60 by default)
  82957. * @returns a SceneOptimizerOptions object
  82958. */
  82959. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82960. var result = new SceneOptimizerOptions(targetFrameRate);
  82961. var priority = 0;
  82962. result.addOptimization(new MergeMeshesOptimization(priority));
  82963. result.addOptimization(new ShadowsOptimization(priority));
  82964. result.addOptimization(new LensFlaresOptimization(priority));
  82965. // Next priority
  82966. priority++;
  82967. result.addOptimization(new PostProcessesOptimization(priority));
  82968. result.addOptimization(new ParticlesOptimization(priority));
  82969. // Next priority
  82970. priority++;
  82971. result.addOptimization(new TextureOptimization(priority, 1024));
  82972. return result;
  82973. };
  82974. /**
  82975. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82976. * @param targetFrameRate defines the target frame rate (60 by default)
  82977. * @returns a SceneOptimizerOptions object
  82978. */
  82979. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82980. var result = new SceneOptimizerOptions(targetFrameRate);
  82981. var priority = 0;
  82982. result.addOptimization(new MergeMeshesOptimization(priority));
  82983. result.addOptimization(new ShadowsOptimization(priority));
  82984. result.addOptimization(new LensFlaresOptimization(priority));
  82985. // Next priority
  82986. priority++;
  82987. result.addOptimization(new PostProcessesOptimization(priority));
  82988. result.addOptimization(new ParticlesOptimization(priority));
  82989. // Next priority
  82990. priority++;
  82991. result.addOptimization(new TextureOptimization(priority, 512));
  82992. // Next priority
  82993. priority++;
  82994. result.addOptimization(new RenderTargetsOptimization(priority));
  82995. // Next priority
  82996. priority++;
  82997. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82998. return result;
  82999. };
  83000. /**
  83001. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83002. * @param targetFrameRate defines the target frame rate (60 by default)
  83003. * @returns a SceneOptimizerOptions object
  83004. */
  83005. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83006. var result = new SceneOptimizerOptions(targetFrameRate);
  83007. var priority = 0;
  83008. result.addOptimization(new MergeMeshesOptimization(priority));
  83009. result.addOptimization(new ShadowsOptimization(priority));
  83010. result.addOptimization(new LensFlaresOptimization(priority));
  83011. // Next priority
  83012. priority++;
  83013. result.addOptimization(new PostProcessesOptimization(priority));
  83014. result.addOptimization(new ParticlesOptimization(priority));
  83015. // Next priority
  83016. priority++;
  83017. result.addOptimization(new TextureOptimization(priority, 256));
  83018. // Next priority
  83019. priority++;
  83020. result.addOptimization(new RenderTargetsOptimization(priority));
  83021. // Next priority
  83022. priority++;
  83023. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83024. return result;
  83025. };
  83026. return SceneOptimizerOptions;
  83027. }());
  83028. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83029. /**
  83030. * Class used to run optimizations in order to reach a target frame rate
  83031. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83032. */
  83033. var SceneOptimizer = /** @class */ (function () {
  83034. /**
  83035. * Creates a new SceneOptimizer
  83036. * @param scene defines the scene to work on
  83037. * @param options defines the options to use with the SceneOptimizer
  83038. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83039. * @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)
  83040. */
  83041. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83042. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83043. if (improvementMode === void 0) { improvementMode = false; }
  83044. var _this = this;
  83045. this._isRunning = false;
  83046. this._currentPriorityLevel = 0;
  83047. this._targetFrameRate = 60;
  83048. this._trackerDuration = 2000;
  83049. this._currentFrameRate = 0;
  83050. this._improvementMode = false;
  83051. /**
  83052. * Defines an observable called when the optimizer reaches the target frame rate
  83053. */
  83054. this.onSuccessObservable = new BABYLON.Observable();
  83055. /**
  83056. * Defines an observable called when the optimizer enables an optimization
  83057. */
  83058. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83059. /**
  83060. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83061. */
  83062. this.onFailureObservable = new BABYLON.Observable();
  83063. if (!options) {
  83064. this._options = new SceneOptimizerOptions();
  83065. }
  83066. else {
  83067. this._options = options;
  83068. }
  83069. if (this._options.targetFrameRate) {
  83070. this._targetFrameRate = this._options.targetFrameRate;
  83071. }
  83072. if (this._options.trackerDuration) {
  83073. this._trackerDuration = this._options.trackerDuration;
  83074. }
  83075. if (autoGeneratePriorities) {
  83076. var priority = 0;
  83077. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83078. var optim = _a[_i];
  83079. optim.priority = priority++;
  83080. }
  83081. }
  83082. this._improvementMode = improvementMode;
  83083. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83084. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83085. _this._sceneDisposeObserver = null;
  83086. _this.dispose();
  83087. });
  83088. }
  83089. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83090. /**
  83091. * Gets a boolean indicating if the optimizer is in improvement mode
  83092. */
  83093. get: function () {
  83094. return this._improvementMode;
  83095. },
  83096. enumerable: true,
  83097. configurable: true
  83098. });
  83099. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83100. /**
  83101. * Gets the current priority level (0 at start)
  83102. */
  83103. get: function () {
  83104. return this._currentPriorityLevel;
  83105. },
  83106. enumerable: true,
  83107. configurable: true
  83108. });
  83109. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83110. /**
  83111. * Gets the current frame rate checked by the SceneOptimizer
  83112. */
  83113. get: function () {
  83114. return this._currentFrameRate;
  83115. },
  83116. enumerable: true,
  83117. configurable: true
  83118. });
  83119. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83120. /**
  83121. * Gets or sets the current target frame rate (60 by default)
  83122. */
  83123. get: function () {
  83124. return this._targetFrameRate;
  83125. },
  83126. /**
  83127. * Gets or sets the current target frame rate (60 by default)
  83128. */
  83129. set: function (value) {
  83130. this._targetFrameRate = value;
  83131. },
  83132. enumerable: true,
  83133. configurable: true
  83134. });
  83135. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83136. /**
  83137. * Gets or sets the current interval between two checks (every 2000ms by default)
  83138. */
  83139. get: function () {
  83140. return this._trackerDuration;
  83141. },
  83142. /**
  83143. * Gets or sets the current interval between two checks (every 2000ms by default)
  83144. */
  83145. set: function (value) {
  83146. this._trackerDuration = value;
  83147. },
  83148. enumerable: true,
  83149. configurable: true
  83150. });
  83151. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83152. /**
  83153. * Gets the list of active optimizations
  83154. */
  83155. get: function () {
  83156. return this._options.optimizations;
  83157. },
  83158. enumerable: true,
  83159. configurable: true
  83160. });
  83161. /**
  83162. * Stops the current optimizer
  83163. */
  83164. SceneOptimizer.prototype.stop = function () {
  83165. this._isRunning = false;
  83166. };
  83167. /**
  83168. * Reset the optimizer to initial step (current priority level = 0)
  83169. */
  83170. SceneOptimizer.prototype.reset = function () {
  83171. this._currentPriorityLevel = 0;
  83172. };
  83173. /**
  83174. * Start the optimizer. By default it will try to reach a specific framerate
  83175. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83176. */
  83177. SceneOptimizer.prototype.start = function () {
  83178. var _this = this;
  83179. if (this._isRunning) {
  83180. return;
  83181. }
  83182. this._isRunning = true;
  83183. // Let's wait for the scene to be ready before running our check
  83184. this._scene.executeWhenReady(function () {
  83185. setTimeout(function () {
  83186. _this._checkCurrentState();
  83187. }, _this._trackerDuration);
  83188. });
  83189. };
  83190. SceneOptimizer.prototype._checkCurrentState = function () {
  83191. var _this = this;
  83192. if (!this._isRunning) {
  83193. return;
  83194. }
  83195. var scene = this._scene;
  83196. var options = this._options;
  83197. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83198. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83199. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83200. this._isRunning = false;
  83201. this.onSuccessObservable.notifyObservers(this);
  83202. return;
  83203. }
  83204. // Apply current level of optimizations
  83205. var allDone = true;
  83206. var noOptimizationApplied = true;
  83207. for (var index = 0; index < options.optimizations.length; index++) {
  83208. var optimization = options.optimizations[index];
  83209. if (optimization.priority === this._currentPriorityLevel) {
  83210. noOptimizationApplied = false;
  83211. allDone = allDone && optimization.apply(scene, this);
  83212. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83213. }
  83214. }
  83215. // If no optimization was applied, this is a failure :(
  83216. if (noOptimizationApplied) {
  83217. this._isRunning = false;
  83218. this.onFailureObservable.notifyObservers(this);
  83219. return;
  83220. }
  83221. // If all optimizations were done, move to next level
  83222. if (allDone) {
  83223. this._currentPriorityLevel++;
  83224. }
  83225. // Let's the system running for a specific amount of time before checking FPS
  83226. scene.executeWhenReady(function () {
  83227. setTimeout(function () {
  83228. _this._checkCurrentState();
  83229. }, _this._trackerDuration);
  83230. });
  83231. };
  83232. /**
  83233. * Release all resources
  83234. */
  83235. SceneOptimizer.prototype.dispose = function () {
  83236. this.stop();
  83237. this.onSuccessObservable.clear();
  83238. this.onFailureObservable.clear();
  83239. this.onNewOptimizationAppliedObservable.clear();
  83240. if (this._sceneDisposeObserver) {
  83241. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83242. }
  83243. };
  83244. /**
  83245. * Helper function to create a SceneOptimizer with one single line of code
  83246. * @param scene defines the scene to work on
  83247. * @param options defines the options to use with the SceneOptimizer
  83248. * @param onSuccess defines a callback to call on success
  83249. * @param onFailure defines a callback to call on failure
  83250. * @returns the new SceneOptimizer object
  83251. */
  83252. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83253. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83254. if (onSuccess) {
  83255. optimizer.onSuccessObservable.add(function () {
  83256. onSuccess();
  83257. });
  83258. }
  83259. if (onFailure) {
  83260. optimizer.onFailureObservable.add(function () {
  83261. onFailure();
  83262. });
  83263. }
  83264. optimizer.start();
  83265. return optimizer;
  83266. };
  83267. return SceneOptimizer;
  83268. }());
  83269. BABYLON.SceneOptimizer = SceneOptimizer;
  83270. })(BABYLON || (BABYLON = {}));
  83271. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83272. var BABYLON;
  83273. (function (BABYLON) {
  83274. var OutlineRenderer = /** @class */ (function () {
  83275. function OutlineRenderer(scene) {
  83276. this.zOffset = 1;
  83277. this._scene = scene;
  83278. }
  83279. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83280. var _this = this;
  83281. if (useOverlay === void 0) { useOverlay = false; }
  83282. var scene = this._scene;
  83283. var engine = this._scene.getEngine();
  83284. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83285. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83286. return;
  83287. }
  83288. var mesh = subMesh.getRenderingMesh();
  83289. var material = subMesh.getMaterial();
  83290. if (!material || !scene.activeCamera) {
  83291. return;
  83292. }
  83293. engine.enableEffect(this._effect);
  83294. // Logarithmic depth
  83295. if (material.useLogarithmicDepth) {
  83296. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83297. }
  83298. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83299. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83300. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83301. // Bones
  83302. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83303. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83304. }
  83305. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83306. // Alpha test
  83307. if (material && material.needAlphaTesting()) {
  83308. var alphaTexture = material.getAlphaTestTexture();
  83309. if (alphaTexture) {
  83310. this._effect.setTexture("diffuseSampler", alphaTexture);
  83311. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83312. }
  83313. }
  83314. engine.setZOffset(-this.zOffset);
  83315. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83316. engine.setZOffset(0);
  83317. };
  83318. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83319. var defines = [];
  83320. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83321. var mesh = subMesh.getMesh();
  83322. var material = subMesh.getMaterial();
  83323. if (material) {
  83324. // Alpha test
  83325. if (material.needAlphaTesting()) {
  83326. defines.push("#define ALPHATEST");
  83327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83328. attribs.push(BABYLON.VertexBuffer.UVKind);
  83329. defines.push("#define UV1");
  83330. }
  83331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83332. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83333. defines.push("#define UV2");
  83334. }
  83335. }
  83336. //Logarithmic depth
  83337. if (material.useLogarithmicDepth) {
  83338. defines.push("#define LOGARITHMICDEPTH");
  83339. }
  83340. }
  83341. // Bones
  83342. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83343. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83344. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83345. if (mesh.numBoneInfluencers > 4) {
  83346. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83347. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83348. }
  83349. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83350. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83351. }
  83352. else {
  83353. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83354. }
  83355. // Instances
  83356. if (useInstances) {
  83357. defines.push("#define INSTANCES");
  83358. attribs.push("world0");
  83359. attribs.push("world1");
  83360. attribs.push("world2");
  83361. attribs.push("world3");
  83362. }
  83363. // Get correct effect
  83364. var join = defines.join("\n");
  83365. if (this._cachedDefines !== join) {
  83366. this._cachedDefines = join;
  83367. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83368. }
  83369. return this._effect.isReady();
  83370. };
  83371. return OutlineRenderer;
  83372. }());
  83373. BABYLON.OutlineRenderer = OutlineRenderer;
  83374. })(BABYLON || (BABYLON = {}));
  83375. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83376. var BABYLON;
  83377. (function (BABYLON) {
  83378. var FaceAdjacencies = /** @class */ (function () {
  83379. function FaceAdjacencies() {
  83380. this.edges = new Array();
  83381. this.edgesConnectedCount = 0;
  83382. }
  83383. return FaceAdjacencies;
  83384. }());
  83385. var EdgesRenderer = /** @class */ (function () {
  83386. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83387. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83388. if (epsilon === void 0) { epsilon = 0.95; }
  83389. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83390. this.edgesWidthScalerForOrthographic = 1000.0;
  83391. this.edgesWidthScalerForPerspective = 50.0;
  83392. this._linesPositions = new Array();
  83393. this._linesNormals = new Array();
  83394. this._linesIndices = new Array();
  83395. this._buffers = {};
  83396. this._checkVerticesInsteadOfIndices = false;
  83397. this._source = source;
  83398. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83399. this._epsilon = epsilon;
  83400. this._prepareRessources();
  83401. this._generateEdgesLines();
  83402. }
  83403. EdgesRenderer.prototype._prepareRessources = function () {
  83404. if (this._lineShader) {
  83405. return;
  83406. }
  83407. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83408. attributes: ["position", "normal"],
  83409. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83410. });
  83411. this._lineShader.disableDepthWrite = true;
  83412. this._lineShader.backFaceCulling = false;
  83413. };
  83414. EdgesRenderer.prototype._rebuild = function () {
  83415. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83416. if (buffer) {
  83417. buffer._rebuild();
  83418. }
  83419. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83420. if (buffer) {
  83421. buffer._rebuild();
  83422. }
  83423. var scene = this._source.getScene();
  83424. var engine = scene.getEngine();
  83425. this._ib = engine.createIndexBuffer(this._linesIndices);
  83426. };
  83427. EdgesRenderer.prototype.dispose = function () {
  83428. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83429. if (buffer) {
  83430. buffer.dispose();
  83431. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83432. }
  83433. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83434. if (buffer) {
  83435. buffer.dispose();
  83436. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83437. }
  83438. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83439. this._lineShader.dispose();
  83440. };
  83441. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83442. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83443. return 0;
  83444. }
  83445. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83446. return 1;
  83447. }
  83448. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83449. return 2;
  83450. }
  83451. return -1;
  83452. };
  83453. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83454. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83455. return 0;
  83456. }
  83457. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83458. return 1;
  83459. }
  83460. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83461. return 2;
  83462. }
  83463. return -1;
  83464. };
  83465. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83466. var needToCreateLine;
  83467. if (edge === undefined) {
  83468. needToCreateLine = true;
  83469. }
  83470. else {
  83471. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83472. needToCreateLine = dotProduct < this._epsilon;
  83473. }
  83474. if (needToCreateLine) {
  83475. var offset = this._linesPositions.length / 3;
  83476. var normal = p0.subtract(p1);
  83477. normal.normalize();
  83478. // Positions
  83479. this._linesPositions.push(p0.x);
  83480. this._linesPositions.push(p0.y);
  83481. this._linesPositions.push(p0.z);
  83482. this._linesPositions.push(p0.x);
  83483. this._linesPositions.push(p0.y);
  83484. this._linesPositions.push(p0.z);
  83485. this._linesPositions.push(p1.x);
  83486. this._linesPositions.push(p1.y);
  83487. this._linesPositions.push(p1.z);
  83488. this._linesPositions.push(p1.x);
  83489. this._linesPositions.push(p1.y);
  83490. this._linesPositions.push(p1.z);
  83491. // Normals
  83492. this._linesNormals.push(p1.x);
  83493. this._linesNormals.push(p1.y);
  83494. this._linesNormals.push(p1.z);
  83495. this._linesNormals.push(-1);
  83496. this._linesNormals.push(p1.x);
  83497. this._linesNormals.push(p1.y);
  83498. this._linesNormals.push(p1.z);
  83499. this._linesNormals.push(1);
  83500. this._linesNormals.push(p0.x);
  83501. this._linesNormals.push(p0.y);
  83502. this._linesNormals.push(p0.z);
  83503. this._linesNormals.push(-1);
  83504. this._linesNormals.push(p0.x);
  83505. this._linesNormals.push(p0.y);
  83506. this._linesNormals.push(p0.z);
  83507. this._linesNormals.push(1);
  83508. // Indices
  83509. this._linesIndices.push(offset);
  83510. this._linesIndices.push(offset + 1);
  83511. this._linesIndices.push(offset + 2);
  83512. this._linesIndices.push(offset);
  83513. this._linesIndices.push(offset + 2);
  83514. this._linesIndices.push(offset + 3);
  83515. }
  83516. };
  83517. EdgesRenderer.prototype._generateEdgesLines = function () {
  83518. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83519. var indices = this._source.getIndices();
  83520. if (!indices || !positions) {
  83521. return;
  83522. }
  83523. // First let's find adjacencies
  83524. var adjacencies = new Array();
  83525. var faceNormals = new Array();
  83526. var index;
  83527. var faceAdjacencies;
  83528. // Prepare faces
  83529. for (index = 0; index < indices.length; index += 3) {
  83530. faceAdjacencies = new FaceAdjacencies();
  83531. var p0Index = indices[index];
  83532. var p1Index = indices[index + 1];
  83533. var p2Index = indices[index + 2];
  83534. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83535. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83536. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83537. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83538. faceNormal.normalize();
  83539. faceNormals.push(faceNormal);
  83540. adjacencies.push(faceAdjacencies);
  83541. }
  83542. // Scan
  83543. for (index = 0; index < adjacencies.length; index++) {
  83544. faceAdjacencies = adjacencies[index];
  83545. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83546. var otherFaceAdjacencies = adjacencies[otherIndex];
  83547. if (faceAdjacencies.edgesConnectedCount === 3) {
  83548. break;
  83549. }
  83550. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83551. continue;
  83552. }
  83553. var otherP0 = indices[otherIndex * 3];
  83554. var otherP1 = indices[otherIndex * 3 + 1];
  83555. var otherP2 = indices[otherIndex * 3 + 2];
  83556. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83557. var otherEdgeIndex = 0;
  83558. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83559. continue;
  83560. }
  83561. switch (edgeIndex) {
  83562. case 0:
  83563. if (this._checkVerticesInsteadOfIndices) {
  83564. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83565. }
  83566. else {
  83567. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83568. }
  83569. break;
  83570. case 1:
  83571. if (this._checkVerticesInsteadOfIndices) {
  83572. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83573. }
  83574. else {
  83575. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83576. }
  83577. break;
  83578. case 2:
  83579. if (this._checkVerticesInsteadOfIndices) {
  83580. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83581. }
  83582. else {
  83583. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83584. }
  83585. break;
  83586. }
  83587. if (otherEdgeIndex === -1) {
  83588. continue;
  83589. }
  83590. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83591. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83592. faceAdjacencies.edgesConnectedCount++;
  83593. otherFaceAdjacencies.edgesConnectedCount++;
  83594. if (faceAdjacencies.edgesConnectedCount === 3) {
  83595. break;
  83596. }
  83597. }
  83598. }
  83599. }
  83600. // Create lines
  83601. for (index = 0; index < adjacencies.length; index++) {
  83602. // 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
  83603. var current = adjacencies[index];
  83604. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83605. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83606. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83607. }
  83608. // Merge into a single mesh
  83609. var engine = this._source.getScene().getEngine();
  83610. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83611. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83612. this._ib = engine.createIndexBuffer(this._linesIndices);
  83613. this._indicesCount = this._linesIndices.length;
  83614. };
  83615. EdgesRenderer.prototype.render = function () {
  83616. var scene = this._source.getScene();
  83617. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83618. return;
  83619. }
  83620. var engine = scene.getEngine();
  83621. this._lineShader._preBind();
  83622. // VBOs
  83623. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83624. scene.resetCachedMaterial();
  83625. this._lineShader.setColor4("color", this._source.edgesColor);
  83626. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83627. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83628. }
  83629. else {
  83630. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83631. }
  83632. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83633. this._lineShader.bind(this._source.getWorldMatrix());
  83634. // Draw order
  83635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83636. this._lineShader.unbind();
  83637. engine.setDepthWrite(true);
  83638. };
  83639. return EdgesRenderer;
  83640. }());
  83641. BABYLON.EdgesRenderer = EdgesRenderer;
  83642. })(BABYLON || (BABYLON = {}));
  83643. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83644. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83645. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83646. s = arguments[i];
  83647. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83648. t[p] = s[p];
  83649. }
  83650. return t;
  83651. };
  83652. var BABYLON;
  83653. (function (BABYLON) {
  83654. /**
  83655. * The effect layer Helps adding post process effect blended with the main pass.
  83656. *
  83657. * This can be for instance use to generate glow or higlight effects on the scene.
  83658. *
  83659. * The effect layer class can not be used directly and is intented to inherited from to be
  83660. * customized per effects.
  83661. */
  83662. var EffectLayer = /** @class */ (function () {
  83663. /**
  83664. * Instantiates a new effect Layer and references it in the scene.
  83665. * @param name The name of the layer
  83666. * @param scene The scene to use the layer in
  83667. */
  83668. function EffectLayer(
  83669. /** The Friendly of the effect in the scene */
  83670. name, scene) {
  83671. this.name = name;
  83672. this._vertexBuffers = {};
  83673. this._maxSize = 0;
  83674. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83675. this._shouldRender = true;
  83676. this._postProcesses = [];
  83677. this._textures = [];
  83678. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83679. /**
  83680. * The clear color of the texture used to generate the glow map.
  83681. */
  83682. this.neutralColor = new BABYLON.Color4();
  83683. /**
  83684. * Specifies wether the highlight layer is enabled or not.
  83685. */
  83686. this.isEnabled = true;
  83687. /**
  83688. * An event triggered when the effect layer has been disposed.
  83689. */
  83690. this.onDisposeObservable = new BABYLON.Observable();
  83691. /**
  83692. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83693. */
  83694. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83695. /**
  83696. * An event triggered when the generated texture is being merged in the scene.
  83697. */
  83698. this.onBeforeComposeObservable = new BABYLON.Observable();
  83699. /**
  83700. * An event triggered when the generated texture has been merged in the scene.
  83701. */
  83702. this.onAfterComposeObservable = new BABYLON.Observable();
  83703. /**
  83704. * An event triggered when the efffect layer changes its size.
  83705. */
  83706. this.onSizeChangedObservable = new BABYLON.Observable();
  83707. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83708. this._engine = scene.getEngine();
  83709. this._maxSize = this._engine.getCaps().maxTextureSize;
  83710. this._scene.effectLayers.push(this);
  83711. // Generate Buffers
  83712. this._generateIndexBuffer();
  83713. this._genrateVertexBuffer();
  83714. }
  83715. Object.defineProperty(EffectLayer.prototype, "camera", {
  83716. /**
  83717. * Gets the camera attached to the layer.
  83718. */
  83719. get: function () {
  83720. return this._effectLayerOptions.camera;
  83721. },
  83722. enumerable: true,
  83723. configurable: true
  83724. });
  83725. /**
  83726. * Initializes the effect layer with the required options.
  83727. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83728. */
  83729. EffectLayer.prototype._init = function (options) {
  83730. // Adapt options
  83731. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83732. this._setMainTextureSize();
  83733. this._createMainTexture();
  83734. this._createTextureAndPostProcesses();
  83735. this._mergeEffect = this._createMergeEffect();
  83736. };
  83737. /**
  83738. * Generates the index buffer of the full screen quad blending to the main canvas.
  83739. */
  83740. EffectLayer.prototype._generateIndexBuffer = function () {
  83741. // Indices
  83742. var indices = [];
  83743. indices.push(0);
  83744. indices.push(1);
  83745. indices.push(2);
  83746. indices.push(0);
  83747. indices.push(2);
  83748. indices.push(3);
  83749. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83750. };
  83751. /**
  83752. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83753. */
  83754. EffectLayer.prototype._genrateVertexBuffer = function () {
  83755. // VBO
  83756. var vertices = [];
  83757. vertices.push(1, 1);
  83758. vertices.push(-1, 1);
  83759. vertices.push(-1, -1);
  83760. vertices.push(1, -1);
  83761. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83763. };
  83764. /**
  83765. * Sets the main texture desired size which is the closest power of two
  83766. * of the engine canvas size.
  83767. */
  83768. EffectLayer.prototype._setMainTextureSize = function () {
  83769. if (this._effectLayerOptions.mainTextureFixedSize) {
  83770. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83771. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83772. }
  83773. else {
  83774. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83775. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83776. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83777. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83778. }
  83779. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83780. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83781. };
  83782. /**
  83783. * Creates the main texture for the effect layer.
  83784. */
  83785. EffectLayer.prototype._createMainTexture = function () {
  83786. var _this = this;
  83787. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83788. width: this._mainTextureDesiredSize.width,
  83789. height: this._mainTextureDesiredSize.height
  83790. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83791. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83792. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83793. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83794. this._mainTexture.anisotropicFilteringLevel = 1;
  83795. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83796. this._mainTexture.renderParticles = false;
  83797. this._mainTexture.renderList = null;
  83798. this._mainTexture.ignoreCameraViewport = true;
  83799. // Custom render function
  83800. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83801. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83802. var index;
  83803. var engine = _this._scene.getEngine();
  83804. if (depthOnlySubMeshes.length) {
  83805. engine.setColorWrite(false);
  83806. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83807. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83808. }
  83809. engine.setColorWrite(true);
  83810. }
  83811. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83812. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83813. }
  83814. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83815. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83816. }
  83817. for (index = 0; index < transparentSubMeshes.length; index++) {
  83818. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83819. }
  83820. };
  83821. this._mainTexture.onClearObservable.add(function (engine) {
  83822. engine.clear(_this.neutralColor, true, true, true);
  83823. });
  83824. };
  83825. /**
  83826. * Checks for the readiness of the element composing the layer.
  83827. * @param subMesh the mesh to check for
  83828. * @param useInstances specify wether or not to use instances to render the mesh
  83829. * @param emissiveTexture the associated emissive texture used to generate the glow
  83830. * @return true if ready otherwise, false
  83831. */
  83832. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83833. var material = subMesh.getMaterial();
  83834. if (!material) {
  83835. return false;
  83836. }
  83837. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83838. return false;
  83839. }
  83840. var defines = [];
  83841. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83842. var mesh = subMesh.getMesh();
  83843. var uv1 = false;
  83844. var uv2 = false;
  83845. // Alpha test
  83846. if (material && material.needAlphaTesting()) {
  83847. var alphaTexture = material.getAlphaTestTexture();
  83848. if (alphaTexture) {
  83849. defines.push("#define ALPHATEST");
  83850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83851. alphaTexture.coordinatesIndex === 1) {
  83852. defines.push("#define DIFFUSEUV2");
  83853. uv2 = true;
  83854. }
  83855. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83856. defines.push("#define DIFFUSEUV1");
  83857. uv1 = true;
  83858. }
  83859. }
  83860. }
  83861. // Emissive
  83862. if (emissiveTexture) {
  83863. defines.push("#define EMISSIVE");
  83864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83865. emissiveTexture.coordinatesIndex === 1) {
  83866. defines.push("#define EMISSIVEUV2");
  83867. uv2 = true;
  83868. }
  83869. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83870. defines.push("#define EMISSIVEUV1");
  83871. uv1 = true;
  83872. }
  83873. }
  83874. if (uv1) {
  83875. attribs.push(BABYLON.VertexBuffer.UVKind);
  83876. defines.push("#define UV1");
  83877. }
  83878. if (uv2) {
  83879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83880. defines.push("#define UV2");
  83881. }
  83882. // Bones
  83883. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83886. if (mesh.numBoneInfluencers > 4) {
  83887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83889. }
  83890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83891. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83892. }
  83893. else {
  83894. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83895. }
  83896. // Instances
  83897. if (useInstances) {
  83898. defines.push("#define INSTANCES");
  83899. attribs.push("world0");
  83900. attribs.push("world1");
  83901. attribs.push("world2");
  83902. attribs.push("world3");
  83903. }
  83904. // Get correct effect
  83905. var join = defines.join("\n");
  83906. if (this._cachedDefines !== join) {
  83907. this._cachedDefines = join;
  83908. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83909. }
  83910. return this._effectLayerMapGenerationEffect.isReady();
  83911. };
  83912. /**
  83913. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83914. */
  83915. EffectLayer.prototype.render = function () {
  83916. var currentEffect = this._mergeEffect;
  83917. // Check
  83918. if (!currentEffect.isReady())
  83919. return;
  83920. for (var i = 0; i < this._postProcesses.length; i++) {
  83921. if (!this._postProcesses[i].isReady()) {
  83922. return;
  83923. }
  83924. }
  83925. var engine = this._scene.getEngine();
  83926. this.onBeforeComposeObservable.notifyObservers(this);
  83927. // Render
  83928. engine.enableEffect(currentEffect);
  83929. engine.setState(false);
  83930. // VBOs
  83931. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83932. // Cache
  83933. var previousAlphaMode = engine.getAlphaMode();
  83934. // Go Blend.
  83935. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83936. // Blends the map on the main canvas.
  83937. this._internalRender(currentEffect);
  83938. // Restore Alpha
  83939. engine.setAlphaMode(previousAlphaMode);
  83940. this.onAfterComposeObservable.notifyObservers(this);
  83941. // Handle size changes.
  83942. var size = this._mainTexture.getSize();
  83943. this._setMainTextureSize();
  83944. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83945. // Recreate RTT and post processes on size change.
  83946. this.onSizeChangedObservable.notifyObservers(this);
  83947. this._disposeTextureAndPostProcesses();
  83948. this._createMainTexture();
  83949. this._createTextureAndPostProcesses();
  83950. }
  83951. };
  83952. /**
  83953. * Determine if a given mesh will be used in the current effect.
  83954. * @param mesh mesh to test
  83955. * @returns true if the mesh will be used
  83956. */
  83957. EffectLayer.prototype.hasMesh = function (mesh) {
  83958. return true;
  83959. };
  83960. /**
  83961. * Returns true if the layer contains information to display, otherwise false.
  83962. * @returns true if the glow layer should be rendered
  83963. */
  83964. EffectLayer.prototype.shouldRender = function () {
  83965. return this.isEnabled && this._shouldRender;
  83966. };
  83967. /**
  83968. * Returns true if the mesh should render, otherwise false.
  83969. * @param mesh The mesh to render
  83970. * @returns true if it should render otherwise false
  83971. */
  83972. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83973. return true;
  83974. };
  83975. /**
  83976. * Returns true if the mesh should render, otherwise false.
  83977. * @param mesh The mesh to render
  83978. * @returns true if it should render otherwise false
  83979. */
  83980. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83981. return true;
  83982. };
  83983. /**
  83984. * Renders the submesh passed in parameter to the generation map.
  83985. */
  83986. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83987. var _this = this;
  83988. if (!this.shouldRender()) {
  83989. return;
  83990. }
  83991. var material = subMesh.getMaterial();
  83992. var mesh = subMesh.getRenderingMesh();
  83993. var scene = this._scene;
  83994. var engine = scene.getEngine();
  83995. if (!material) {
  83996. return;
  83997. }
  83998. // Do not block in blend mode.
  83999. if (material.needAlphaBlendingForMesh(mesh)) {
  84000. return;
  84001. }
  84002. // Culling
  84003. engine.setState(material.backFaceCulling);
  84004. // Managing instances
  84005. var batch = mesh._getInstancesRenderList(subMesh._id);
  84006. if (batch.mustReturn) {
  84007. return;
  84008. }
  84009. // Early Exit per mesh
  84010. if (!this._shouldRenderMesh(mesh)) {
  84011. return;
  84012. }
  84013. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84014. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84015. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84016. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84017. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84018. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84019. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84020. // Alpha test
  84021. if (material && material.needAlphaTesting()) {
  84022. var alphaTexture = material.getAlphaTestTexture();
  84023. if (alphaTexture) {
  84024. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84025. var textureMatrix = alphaTexture.getTextureMatrix();
  84026. if (textureMatrix) {
  84027. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84028. }
  84029. }
  84030. }
  84031. // Glow emissive only
  84032. if (this._emissiveTextureAndColor.texture) {
  84033. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84034. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84035. }
  84036. // Bones
  84037. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84038. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84039. }
  84040. // Draw
  84041. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84042. }
  84043. else {
  84044. // Need to reset refresh rate of the shadowMap
  84045. this._mainTexture.resetRefreshCounter();
  84046. }
  84047. };
  84048. /**
  84049. * Rebuild the required buffers.
  84050. * @ignore Internal use only.
  84051. */
  84052. EffectLayer.prototype._rebuild = function () {
  84053. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84054. if (vb) {
  84055. vb._rebuild();
  84056. }
  84057. this._generateIndexBuffer();
  84058. };
  84059. /**
  84060. * Dispose only the render target textures and post process.
  84061. */
  84062. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84063. this._mainTexture.dispose();
  84064. for (var i = 0; i < this._postProcesses.length; i++) {
  84065. if (this._postProcesses[i]) {
  84066. this._postProcesses[i].dispose();
  84067. }
  84068. }
  84069. this._postProcesses = [];
  84070. for (var i = 0; i < this._textures.length; i++) {
  84071. if (this._textures[i]) {
  84072. this._textures[i].dispose();
  84073. }
  84074. }
  84075. this._textures = [];
  84076. };
  84077. /**
  84078. * Dispose the highlight layer and free resources.
  84079. */
  84080. EffectLayer.prototype.dispose = function () {
  84081. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84082. if (vertexBuffer) {
  84083. vertexBuffer.dispose();
  84084. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84085. }
  84086. if (this._indexBuffer) {
  84087. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84088. this._indexBuffer = null;
  84089. }
  84090. // Clean textures and post processes
  84091. this._disposeTextureAndPostProcesses();
  84092. // Remove from scene
  84093. var index = this._scene.effectLayers.indexOf(this, 0);
  84094. if (index > -1) {
  84095. this._scene.effectLayers.splice(index, 1);
  84096. }
  84097. // Callback
  84098. this.onDisposeObservable.notifyObservers(this);
  84099. this.onDisposeObservable.clear();
  84100. this.onBeforeRenderMainTextureObservable.clear();
  84101. this.onBeforeComposeObservable.clear();
  84102. this.onAfterComposeObservable.clear();
  84103. this.onSizeChangedObservable.clear();
  84104. };
  84105. return EffectLayer;
  84106. }());
  84107. BABYLON.EffectLayer = EffectLayer;
  84108. })(BABYLON || (BABYLON = {}));
  84109. //# sourceMappingURL=babylon.effectLayer.js.map
  84110. var BABYLON;
  84111. (function (BABYLON) {
  84112. /**
  84113. * Special Glow Blur post process only blurring the alpha channel
  84114. * It enforces keeping the most luminous color in the color channel.
  84115. */
  84116. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84117. __extends(GlowBlurPostProcess, _super);
  84118. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84120. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84121. _this.direction = direction;
  84122. _this.kernel = kernel;
  84123. _this.onApplyObservable.add(function (effect) {
  84124. effect.setFloat2("screenSize", _this.width, _this.height);
  84125. effect.setVector2("direction", _this.direction);
  84126. effect.setFloat("blurWidth", _this.kernel);
  84127. });
  84128. return _this;
  84129. }
  84130. return GlowBlurPostProcess;
  84131. }(BABYLON.PostProcess));
  84132. /**
  84133. * The highlight layer Helps adding a glow effect around a mesh.
  84134. *
  84135. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84136. * glowy meshes to your scene.
  84137. *
  84138. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84139. */
  84140. var HighlightLayer = /** @class */ (function (_super) {
  84141. __extends(HighlightLayer, _super);
  84142. /**
  84143. * Instantiates a new highlight Layer and references it to the scene..
  84144. * @param name The name of the layer
  84145. * @param scene The scene to use the layer in
  84146. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84147. */
  84148. function HighlightLayer(name, scene, options) {
  84149. var _this = _super.call(this, name, scene) || this;
  84150. _this.name = name;
  84151. /**
  84152. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84153. */
  84154. _this.innerGlow = true;
  84155. /**
  84156. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84157. */
  84158. _this.outerGlow = true;
  84159. /**
  84160. * An event triggered when the highlight layer is being blurred.
  84161. */
  84162. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84163. /**
  84164. * An event triggered when the highlight layer has been blurred.
  84165. */
  84166. _this.onAfterBlurObservable = new BABYLON.Observable();
  84167. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84168. _this._meshes = {};
  84169. _this._excludedMeshes = {};
  84170. _this.neutralColor = HighlightLayer.NeutralColor;
  84171. // Warn on stencil
  84172. if (!_this._engine.isStencilEnable) {
  84173. 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 }");
  84174. }
  84175. // Adapt options
  84176. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84177. // Initialize the layer
  84178. _this._init({
  84179. alphaBlendingMode: _this._options.alphaBlendingMode,
  84180. camera: _this._options.camera,
  84181. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84182. mainTextureRatio: _this._options.mainTextureRatio
  84183. });
  84184. // Do not render as long as no meshes have been added
  84185. _this._shouldRender = false;
  84186. return _this;
  84187. }
  84188. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84189. /**
  84190. * Gets the horizontal size of the blur.
  84191. */
  84192. get: function () {
  84193. return this._horizontalBlurPostprocess.kernel;
  84194. },
  84195. /**
  84196. * Specifies the horizontal size of the blur.
  84197. */
  84198. set: function (value) {
  84199. this._horizontalBlurPostprocess.kernel = value;
  84200. },
  84201. enumerable: true,
  84202. configurable: true
  84203. });
  84204. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84205. /**
  84206. * Gets the vertical size of the blur.
  84207. */
  84208. get: function () {
  84209. return this._verticalBlurPostprocess.kernel;
  84210. },
  84211. /**
  84212. * Specifies the vertical size of the blur.
  84213. */
  84214. set: function (value) {
  84215. this._verticalBlurPostprocess.kernel = value;
  84216. },
  84217. enumerable: true,
  84218. configurable: true
  84219. });
  84220. /**
  84221. * Get the effect name of the layer.
  84222. * @return The effect name
  84223. */
  84224. HighlightLayer.prototype.getEffectName = function () {
  84225. return HighlightLayer.EffectName;
  84226. };
  84227. /**
  84228. * Create the merge effect. This is the shader use to blit the information back
  84229. * to the main canvas at the end of the scene rendering.
  84230. */
  84231. HighlightLayer.prototype._createMergeEffect = function () {
  84232. // Effect
  84233. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84234. };
  84235. /**
  84236. * Creates the render target textures and post processes used in the highlight layer.
  84237. */
  84238. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84239. var _this = this;
  84240. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84241. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84242. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84243. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84244. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84245. width: blurTextureWidth,
  84246. height: blurTextureHeight
  84247. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84248. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84249. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84250. this._blurTexture.anisotropicFilteringLevel = 16;
  84251. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84252. this._blurTexture.renderParticles = false;
  84253. this._blurTexture.ignoreCameraViewport = true;
  84254. this._textures = [this._blurTexture];
  84255. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84256. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84257. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84258. effect.setTexture("textureSampler", _this._mainTexture);
  84259. });
  84260. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84261. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84262. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84263. });
  84264. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84265. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84266. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84267. });
  84268. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84269. }
  84270. else {
  84271. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84272. width: blurTextureWidth,
  84273. height: blurTextureHeight
  84274. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84275. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84276. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84277. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84278. effect.setTexture("textureSampler", _this._mainTexture);
  84279. });
  84280. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84281. width: blurTextureWidth,
  84282. height: blurTextureHeight
  84283. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84284. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84285. }
  84286. this._mainTexture.onAfterUnbindObservable.add(function () {
  84287. _this.onBeforeBlurObservable.notifyObservers(_this);
  84288. var internalTexture = _this._blurTexture.getInternalTexture();
  84289. if (internalTexture) {
  84290. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84291. }
  84292. _this.onAfterBlurObservable.notifyObservers(_this);
  84293. });
  84294. // Prevent autoClear.
  84295. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84296. };
  84297. /**
  84298. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84299. */
  84300. HighlightLayer.prototype.needStencil = function () {
  84301. return true;
  84302. };
  84303. /**
  84304. * Checks for the readiness of the element composing the layer.
  84305. * @param subMesh the mesh to check for
  84306. * @param useInstances specify wether or not to use instances to render the mesh
  84307. * @param emissiveTexture the associated emissive texture used to generate the glow
  84308. * @return true if ready otherwise, false
  84309. */
  84310. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84311. var material = subMesh.getMaterial();
  84312. var mesh = subMesh.getRenderingMesh();
  84313. if (!material || !mesh || !this._meshes) {
  84314. return false;
  84315. }
  84316. var emissiveTexture = null;
  84317. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84318. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84319. emissiveTexture = material.emissiveTexture;
  84320. }
  84321. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84322. };
  84323. /**
  84324. * Implementation specific of rendering the generating effect on the main canvas.
  84325. * @param effect The effect used to render through
  84326. */
  84327. HighlightLayer.prototype._internalRender = function (effect) {
  84328. // Texture
  84329. effect.setTexture("textureSampler", this._blurTexture);
  84330. // Cache
  84331. var engine = this._engine;
  84332. var previousStencilBuffer = engine.getStencilBuffer();
  84333. var previousStencilFunction = engine.getStencilFunction();
  84334. var previousStencilMask = engine.getStencilMask();
  84335. var previousStencilOperationPass = engine.getStencilOperationPass();
  84336. var previousStencilOperationFail = engine.getStencilOperationFail();
  84337. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84338. var previousStencilReference = engine.getStencilFunctionReference();
  84339. // Stencil operations
  84340. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84341. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84342. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84343. // Draw order
  84344. engine.setStencilMask(0x00);
  84345. engine.setStencilBuffer(true);
  84346. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84347. // 2 passes inner outer
  84348. if (this.outerGlow) {
  84349. effect.setFloat("offset", 0);
  84350. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84352. }
  84353. if (this.innerGlow) {
  84354. effect.setFloat("offset", 1);
  84355. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84356. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84357. }
  84358. // Restore Cache
  84359. engine.setStencilFunction(previousStencilFunction);
  84360. engine.setStencilMask(previousStencilMask);
  84361. engine.setStencilBuffer(previousStencilBuffer);
  84362. engine.setStencilOperationPass(previousStencilOperationPass);
  84363. engine.setStencilOperationFail(previousStencilOperationFail);
  84364. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84365. engine.setStencilFunctionReference(previousStencilReference);
  84366. };
  84367. /**
  84368. * Returns true if the layer contains information to display, otherwise false.
  84369. */
  84370. HighlightLayer.prototype.shouldRender = function () {
  84371. if (_super.prototype.shouldRender.call(this)) {
  84372. return this._meshes ? true : false;
  84373. }
  84374. return false;
  84375. };
  84376. /**
  84377. * Returns true if the mesh should render, otherwise false.
  84378. * @param mesh The mesh to render
  84379. * @returns true if it should render otherwise false
  84380. */
  84381. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84382. // Excluded Mesh
  84383. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84384. return false;
  84385. }
  84386. ;
  84387. return true;
  84388. };
  84389. /**
  84390. * Sets the required values for both the emissive texture and and the main color.
  84391. */
  84392. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84393. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84394. if (highlightLayerMesh) {
  84395. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84396. }
  84397. else {
  84398. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84399. }
  84400. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84401. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84402. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84403. }
  84404. else {
  84405. this._emissiveTextureAndColor.texture = null;
  84406. }
  84407. };
  84408. /**
  84409. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84410. * @param mesh The mesh to exclude from the highlight layer
  84411. */
  84412. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84413. if (!this._excludedMeshes) {
  84414. return;
  84415. }
  84416. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84417. if (!meshExcluded) {
  84418. this._excludedMeshes[mesh.uniqueId] = {
  84419. mesh: mesh,
  84420. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84421. mesh.getEngine().setStencilBuffer(false);
  84422. }),
  84423. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84424. mesh.getEngine().setStencilBuffer(true);
  84425. }),
  84426. };
  84427. }
  84428. };
  84429. /**
  84430. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84431. * @param mesh The mesh to highlight
  84432. */
  84433. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84434. if (!this._excludedMeshes) {
  84435. return;
  84436. }
  84437. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84438. if (meshExcluded) {
  84439. if (meshExcluded.beforeRender) {
  84440. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84441. }
  84442. if (meshExcluded.afterRender) {
  84443. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84444. }
  84445. }
  84446. this._excludedMeshes[mesh.uniqueId] = null;
  84447. };
  84448. /**
  84449. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84450. * @param mesh mesh to test
  84451. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84452. */
  84453. HighlightLayer.prototype.hasMesh = function (mesh) {
  84454. if (!this._meshes) {
  84455. return false;
  84456. }
  84457. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84458. };
  84459. /**
  84460. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84461. * @param mesh The mesh to highlight
  84462. * @param color The color of the highlight
  84463. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84464. */
  84465. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84466. var _this = this;
  84467. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84468. if (!this._meshes) {
  84469. return;
  84470. }
  84471. var meshHighlight = this._meshes[mesh.uniqueId];
  84472. if (meshHighlight) {
  84473. meshHighlight.color = color;
  84474. }
  84475. else {
  84476. this._meshes[mesh.uniqueId] = {
  84477. mesh: mesh,
  84478. color: color,
  84479. // Lambda required for capture due to Observable this context
  84480. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84481. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84482. _this._defaultStencilReference(mesh);
  84483. }
  84484. else {
  84485. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84486. }
  84487. }),
  84488. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84489. glowEmissiveOnly: glowEmissiveOnly
  84490. };
  84491. }
  84492. this._shouldRender = true;
  84493. };
  84494. /**
  84495. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84496. * @param mesh The mesh to highlight
  84497. */
  84498. HighlightLayer.prototype.removeMesh = function (mesh) {
  84499. if (!this._meshes) {
  84500. return;
  84501. }
  84502. var meshHighlight = this._meshes[mesh.uniqueId];
  84503. if (meshHighlight) {
  84504. if (meshHighlight.observerHighlight) {
  84505. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84506. }
  84507. if (meshHighlight.observerDefault) {
  84508. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84509. }
  84510. delete this._meshes[mesh.uniqueId];
  84511. }
  84512. this._shouldRender = false;
  84513. for (var meshHighlightToCheck in this._meshes) {
  84514. if (this._meshes[meshHighlightToCheck]) {
  84515. this._shouldRender = true;
  84516. break;
  84517. }
  84518. }
  84519. };
  84520. /**
  84521. * Force the stencil to the normal expected value for none glowing parts
  84522. */
  84523. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84524. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84525. };
  84526. /**
  84527. * Free any resources and references associated to a mesh.
  84528. * Internal use
  84529. * @param mesh The mesh to free.
  84530. */
  84531. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84532. this.removeMesh(mesh);
  84533. this.removeExcludedMesh(mesh);
  84534. };
  84535. /**
  84536. * Dispose the highlight layer and free resources.
  84537. */
  84538. HighlightLayer.prototype.dispose = function () {
  84539. if (this._meshes) {
  84540. // Clean mesh references
  84541. for (var id in this._meshes) {
  84542. var meshHighlight = this._meshes[id];
  84543. if (meshHighlight && meshHighlight.mesh) {
  84544. if (meshHighlight.observerHighlight) {
  84545. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84546. }
  84547. if (meshHighlight.observerDefault) {
  84548. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84549. }
  84550. }
  84551. }
  84552. this._meshes = null;
  84553. }
  84554. if (this._excludedMeshes) {
  84555. for (var id in this._excludedMeshes) {
  84556. var meshHighlight = this._excludedMeshes[id];
  84557. if (meshHighlight) {
  84558. if (meshHighlight.beforeRender) {
  84559. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84560. }
  84561. if (meshHighlight.afterRender) {
  84562. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84563. }
  84564. }
  84565. }
  84566. this._excludedMeshes = null;
  84567. }
  84568. _super.prototype.dispose.call(this);
  84569. };
  84570. /**
  84571. * Effect Name of the highlight layer.
  84572. */
  84573. HighlightLayer.EffectName = "HighlightLayer";
  84574. /**
  84575. * The neutral color used during the preparation of the glow effect.
  84576. * This is black by default as the blend operation is a blend operation.
  84577. */
  84578. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84579. /**
  84580. * Stencil value used for glowing meshes.
  84581. */
  84582. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84583. /**
  84584. * Stencil value used for the other meshes in the scene.
  84585. */
  84586. HighlightLayer.NormalMeshStencilReference = 0x01;
  84587. return HighlightLayer;
  84588. }(BABYLON.EffectLayer));
  84589. BABYLON.HighlightLayer = HighlightLayer;
  84590. })(BABYLON || (BABYLON = {}));
  84591. //# sourceMappingURL=babylon.highlightLayer.js.map
  84592. var BABYLON;
  84593. (function (BABYLON) {
  84594. /**
  84595. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84596. *
  84597. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84598. * glowy meshes to your scene.
  84599. *
  84600. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84601. */
  84602. var GlowLayer = /** @class */ (function (_super) {
  84603. __extends(GlowLayer, _super);
  84604. /**
  84605. * Instantiates a new glow Layer and references it to the scene.
  84606. * @param name The name of the layer
  84607. * @param scene The scene to use the layer in
  84608. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84609. */
  84610. function GlowLayer(name, scene, options) {
  84611. var _this = _super.call(this, name, scene) || this;
  84612. _this.name = name;
  84613. _this._intensity = 1.0;
  84614. _this._includedOnlyMeshes = [];
  84615. _this._excludedMeshes = [];
  84616. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84617. // Adapt options
  84618. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84619. // Initialize the layer
  84620. _this._init({
  84621. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84622. camera: _this._options.camera,
  84623. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84624. mainTextureRatio: _this._options.mainTextureRatio
  84625. });
  84626. return _this;
  84627. }
  84628. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84629. /**
  84630. * Gets the kernel size of the blur.
  84631. */
  84632. get: function () {
  84633. return this._horizontalBlurPostprocess1.kernel;
  84634. },
  84635. /**
  84636. * Sets the kernel size of the blur.
  84637. */
  84638. set: function (value) {
  84639. this._horizontalBlurPostprocess1.kernel = value;
  84640. this._verticalBlurPostprocess1.kernel = value;
  84641. this._horizontalBlurPostprocess2.kernel = value;
  84642. this._verticalBlurPostprocess2.kernel = value;
  84643. },
  84644. enumerable: true,
  84645. configurable: true
  84646. });
  84647. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84648. /**
  84649. * Gets the glow intensity.
  84650. */
  84651. get: function () {
  84652. return this._intensity;
  84653. },
  84654. /**
  84655. * Sets the glow intensity.
  84656. */
  84657. set: function (value) {
  84658. this._intensity = value;
  84659. },
  84660. enumerable: true,
  84661. configurable: true
  84662. });
  84663. /**
  84664. * Get the effect name of the layer.
  84665. * @return The effect name
  84666. */
  84667. GlowLayer.prototype.getEffectName = function () {
  84668. return GlowLayer.EffectName;
  84669. };
  84670. /**
  84671. * Create the merge effect. This is the shader use to blit the information back
  84672. * to the main canvas at the end of the scene rendering.
  84673. */
  84674. GlowLayer.prototype._createMergeEffect = function () {
  84675. // Effect
  84676. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84677. };
  84678. /**
  84679. * Creates the render target textures and post processes used in the glow layer.
  84680. */
  84681. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84682. var _this = this;
  84683. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84684. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84685. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84686. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84687. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84688. width: blurTextureWidth,
  84689. height: blurTextureHeight
  84690. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84691. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84692. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84693. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84694. this._blurTexture1.renderParticles = false;
  84695. this._blurTexture1.ignoreCameraViewport = true;
  84696. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84697. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84698. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84699. width: blurTextureWidth2,
  84700. height: blurTextureHeight2
  84701. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84702. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84703. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84704. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84705. this._blurTexture2.renderParticles = false;
  84706. this._blurTexture2.ignoreCameraViewport = true;
  84707. this._textures = [this._blurTexture1, this._blurTexture2];
  84708. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84709. width: blurTextureWidth,
  84710. height: blurTextureHeight
  84711. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84712. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84713. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84714. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84715. effect.setTexture("textureSampler", _this._mainTexture);
  84716. });
  84717. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84718. width: blurTextureWidth,
  84719. height: blurTextureHeight
  84720. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84721. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84722. width: blurTextureWidth2,
  84723. height: blurTextureHeight2
  84724. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84725. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84726. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84727. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84728. effect.setTexture("textureSampler", _this._blurTexture1);
  84729. });
  84730. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84731. width: blurTextureWidth2,
  84732. height: blurTextureHeight2
  84733. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84734. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84735. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84736. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84737. this._mainTexture.samples = this._options.mainTextureSamples;
  84738. this._mainTexture.onAfterUnbindObservable.add(function () {
  84739. var internalTexture = _this._blurTexture1.getInternalTexture();
  84740. if (internalTexture) {
  84741. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84742. internalTexture = _this._blurTexture2.getInternalTexture();
  84743. if (internalTexture) {
  84744. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84745. }
  84746. }
  84747. });
  84748. // Prevent autoClear.
  84749. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84750. };
  84751. /**
  84752. * Checks for the readiness of the element composing the layer.
  84753. * @param subMesh the mesh to check for
  84754. * @param useInstances specify wether or not to use instances to render the mesh
  84755. * @param emissiveTexture the associated emissive texture used to generate the glow
  84756. * @return true if ready otherwise, false
  84757. */
  84758. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84759. var material = subMesh.getMaterial();
  84760. var mesh = subMesh.getRenderingMesh();
  84761. if (!material || !mesh) {
  84762. return false;
  84763. }
  84764. var emissiveTexture = material.emissiveTexture;
  84765. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84766. };
  84767. /**
  84768. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84769. */
  84770. GlowLayer.prototype.needStencil = function () {
  84771. return false;
  84772. };
  84773. /**
  84774. * Implementation specific of rendering the generating effect on the main canvas.
  84775. * @param effect The effect used to render through
  84776. */
  84777. GlowLayer.prototype._internalRender = function (effect) {
  84778. // Texture
  84779. effect.setTexture("textureSampler", this._blurTexture1);
  84780. effect.setTexture("textureSampler2", this._blurTexture2);
  84781. effect.setFloat("offset", this._intensity);
  84782. // Cache
  84783. var engine = this._engine;
  84784. var previousStencilBuffer = engine.getStencilBuffer();
  84785. // Draw order
  84786. engine.setStencilBuffer(false);
  84787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84788. // Draw order
  84789. engine.setStencilBuffer(previousStencilBuffer);
  84790. };
  84791. /**
  84792. * Sets the required values for both the emissive texture and and the main color.
  84793. */
  84794. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84795. var textureLevel = 1.0;
  84796. if (this.customEmissiveTextureSelector) {
  84797. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84798. }
  84799. else {
  84800. if (material) {
  84801. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84802. if (this._emissiveTextureAndColor.texture) {
  84803. textureLevel = this._emissiveTextureAndColor.texture.level;
  84804. }
  84805. }
  84806. else {
  84807. this._emissiveTextureAndColor.texture = null;
  84808. }
  84809. }
  84810. if (this.customEmissiveColorSelector) {
  84811. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84812. }
  84813. else {
  84814. if (material.emissiveColor) {
  84815. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84816. }
  84817. else {
  84818. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84819. }
  84820. }
  84821. };
  84822. /**
  84823. * Returns true if the mesh should render, otherwise false.
  84824. * @param mesh The mesh to render
  84825. * @returns true if it should render otherwise false
  84826. */
  84827. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84828. return this.hasMesh(mesh);
  84829. };
  84830. /**
  84831. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84832. * @param mesh The mesh to exclude from the glow layer
  84833. */
  84834. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84835. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84836. this._excludedMeshes.push(mesh.uniqueId);
  84837. }
  84838. };
  84839. /**
  84840. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84841. * @param mesh The mesh to remove
  84842. */
  84843. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84844. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84845. if (index !== -1) {
  84846. this._excludedMeshes.splice(index, 1);
  84847. }
  84848. };
  84849. /**
  84850. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84851. * @param mesh The mesh to include in the glow layer
  84852. */
  84853. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84854. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84855. this._includedOnlyMeshes.push(mesh.uniqueId);
  84856. }
  84857. };
  84858. /**
  84859. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84860. * @param mesh The mesh to remove
  84861. */
  84862. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84863. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84864. if (index !== -1) {
  84865. this._includedOnlyMeshes.splice(index, 1);
  84866. }
  84867. };
  84868. /**
  84869. * Determine if a given mesh will be used in the glow layer
  84870. * @param mesh The mesh to test
  84871. * @returns true if the mesh will be highlighted by the current glow layer
  84872. */
  84873. GlowLayer.prototype.hasMesh = function (mesh) {
  84874. // Included Mesh
  84875. if (this._includedOnlyMeshes.length) {
  84876. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84877. }
  84878. ;
  84879. // Excluded Mesh
  84880. if (this._excludedMeshes.length) {
  84881. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84882. }
  84883. ;
  84884. return true;
  84885. };
  84886. /**
  84887. * Free any resources and references associated to a mesh.
  84888. * Internal use
  84889. * @param mesh The mesh to free.
  84890. */
  84891. GlowLayer.prototype._disposeMesh = function (mesh) {
  84892. this.removeIncludedOnlyMesh(mesh);
  84893. this.removeExcludedMesh(mesh);
  84894. };
  84895. /**
  84896. * Effect Name of the layer.
  84897. */
  84898. GlowLayer.EffectName = "GlowLayer";
  84899. /**
  84900. * The default blur kernel size used for the glow.
  84901. */
  84902. GlowLayer.DefaultBlurKernelSize = 32;
  84903. /**
  84904. * The default texture size ratio used for the glow.
  84905. */
  84906. GlowLayer.DefaultTextureRatio = 0.5;
  84907. return GlowLayer;
  84908. }(BABYLON.EffectLayer));
  84909. BABYLON.GlowLayer = GlowLayer;
  84910. })(BABYLON || (BABYLON = {}));
  84911. //# sourceMappingURL=babylon.glowLayer.js.map
  84912. var BABYLON;
  84913. (function (BABYLON) {
  84914. /**
  84915. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84916. */
  84917. var AssetTaskState;
  84918. (function (AssetTaskState) {
  84919. /**
  84920. * Initialization
  84921. */
  84922. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84923. /**
  84924. * Running
  84925. */
  84926. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84927. /**
  84928. * Done
  84929. */
  84930. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84931. /**
  84932. * Error
  84933. */
  84934. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84935. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84936. /**
  84937. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84938. */
  84939. var AbstractAssetTask = /** @class */ (function () {
  84940. /**
  84941. * Creates a new {BABYLON.AssetsManager}
  84942. * @param name defines the name of the task
  84943. */
  84944. function AbstractAssetTask(
  84945. /**
  84946. * Task name
  84947. */ name) {
  84948. this.name = name;
  84949. this._isCompleted = false;
  84950. this._taskState = AssetTaskState.INIT;
  84951. }
  84952. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84953. /**
  84954. * Get if the task is completed
  84955. */
  84956. get: function () {
  84957. return this._isCompleted;
  84958. },
  84959. enumerable: true,
  84960. configurable: true
  84961. });
  84962. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84963. /**
  84964. * Gets the current state of the task
  84965. */
  84966. get: function () {
  84967. return this._taskState;
  84968. },
  84969. enumerable: true,
  84970. configurable: true
  84971. });
  84972. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84973. /**
  84974. * Gets the current error object (if task is in error)
  84975. */
  84976. get: function () {
  84977. return this._errorObject;
  84978. },
  84979. enumerable: true,
  84980. configurable: true
  84981. });
  84982. /**
  84983. * Internal only
  84984. * @ignore
  84985. */
  84986. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84987. if (this._errorObject) {
  84988. return;
  84989. }
  84990. this._errorObject = {
  84991. message: message,
  84992. exception: exception
  84993. };
  84994. };
  84995. /**
  84996. * Execute the current task
  84997. * @param scene defines the scene where you want your assets to be loaded
  84998. * @param onSuccess is a callback called when the task is successfully executed
  84999. * @param onError is a callback called if an error occurs
  85000. */
  85001. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85002. var _this = this;
  85003. this._taskState = AssetTaskState.RUNNING;
  85004. this.runTask(scene, function () {
  85005. _this.onDoneCallback(onSuccess, onError);
  85006. }, function (msg, exception) {
  85007. _this.onErrorCallback(onError, msg, exception);
  85008. });
  85009. };
  85010. /**
  85011. * Execute the current task
  85012. * @param scene defines the scene where you want your assets to be loaded
  85013. * @param onSuccess is a callback called when the task is successfully executed
  85014. * @param onError is a callback called if an error occurs
  85015. */
  85016. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85017. throw new Error("runTask is not implemented");
  85018. };
  85019. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85020. this._taskState = AssetTaskState.ERROR;
  85021. this._errorObject = {
  85022. message: message,
  85023. exception: exception
  85024. };
  85025. if (this.onError) {
  85026. this.onError(this, message, exception);
  85027. }
  85028. onError();
  85029. };
  85030. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85031. try {
  85032. this._taskState = AssetTaskState.DONE;
  85033. this._isCompleted = true;
  85034. if (this.onSuccess) {
  85035. this.onSuccess(this);
  85036. }
  85037. onSuccess();
  85038. }
  85039. catch (e) {
  85040. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85041. }
  85042. };
  85043. return AbstractAssetTask;
  85044. }());
  85045. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85046. /**
  85047. * Class used to share progress information about assets loading
  85048. */
  85049. var AssetsProgressEvent = /** @class */ (function () {
  85050. /**
  85051. * Creates a {BABYLON.AssetsProgressEvent}
  85052. * @param remainingCount defines the number of remaining tasks to process
  85053. * @param totalCount defines the total number of tasks
  85054. * @param task defines the task that was just processed
  85055. */
  85056. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85057. this.remainingCount = remainingCount;
  85058. this.totalCount = totalCount;
  85059. this.task = task;
  85060. }
  85061. return AssetsProgressEvent;
  85062. }());
  85063. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85064. /**
  85065. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85066. */
  85067. var MeshAssetTask = /** @class */ (function (_super) {
  85068. __extends(MeshAssetTask, _super);
  85069. /**
  85070. * Creates a new {BABYLON.MeshAssetTask}
  85071. * @param name defines the name of the task
  85072. * @param meshesNames defines the list of mesh's names you want to load
  85073. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85074. * @param sceneFilename defines the filename of the scene to load from
  85075. */
  85076. function MeshAssetTask(
  85077. /**
  85078. * Defines the name of the task
  85079. */
  85080. name,
  85081. /**
  85082. * Defines the list of mesh's names you want to load
  85083. */
  85084. meshesNames,
  85085. /**
  85086. * Defines the root url to use as a base to load your meshes and associated resources
  85087. */
  85088. rootUrl,
  85089. /**
  85090. * Defines the filename of the scene to load from
  85091. */
  85092. sceneFilename) {
  85093. var _this = _super.call(this, name) || this;
  85094. _this.name = name;
  85095. _this.meshesNames = meshesNames;
  85096. _this.rootUrl = rootUrl;
  85097. _this.sceneFilename = sceneFilename;
  85098. return _this;
  85099. }
  85100. /**
  85101. * Execute the current task
  85102. * @param scene defines the scene where you want your assets to be loaded
  85103. * @param onSuccess is a callback called when the task is successfully executed
  85104. * @param onError is a callback called if an error occurs
  85105. */
  85106. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85107. var _this = this;
  85108. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85109. _this.loadedMeshes = meshes;
  85110. _this.loadedParticleSystems = particleSystems;
  85111. _this.loadedSkeletons = skeletons;
  85112. onSuccess();
  85113. }, null, function (scene, message, exception) {
  85114. onError(message, exception);
  85115. });
  85116. };
  85117. return MeshAssetTask;
  85118. }(AbstractAssetTask));
  85119. BABYLON.MeshAssetTask = MeshAssetTask;
  85120. /**
  85121. * Define a task used by {BABYLON.AssetsManager} to load text content
  85122. */
  85123. var TextFileAssetTask = /** @class */ (function (_super) {
  85124. __extends(TextFileAssetTask, _super);
  85125. /**
  85126. * Creates a new TextFileAssetTask object
  85127. * @param name defines the name of the task
  85128. * @param url defines the location of the file to load
  85129. */
  85130. function TextFileAssetTask(
  85131. /**
  85132. * Defines the name of the task
  85133. */
  85134. name,
  85135. /**
  85136. * Defines the location of the file to load
  85137. */
  85138. url) {
  85139. var _this = _super.call(this, name) || this;
  85140. _this.name = name;
  85141. _this.url = url;
  85142. return _this;
  85143. }
  85144. /**
  85145. * Execute the current task
  85146. * @param scene defines the scene where you want your assets to be loaded
  85147. * @param onSuccess is a callback called when the task is successfully executed
  85148. * @param onError is a callback called if an error occurs
  85149. */
  85150. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85151. var _this = this;
  85152. scene._loadFile(this.url, function (data) {
  85153. _this.text = data;
  85154. onSuccess();
  85155. }, undefined, false, false, function (request, exception) {
  85156. if (request) {
  85157. onError(request.status + " " + request.statusText, exception);
  85158. }
  85159. });
  85160. };
  85161. return TextFileAssetTask;
  85162. }(AbstractAssetTask));
  85163. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85164. /**
  85165. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85166. */
  85167. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85168. __extends(BinaryFileAssetTask, _super);
  85169. /**
  85170. * Creates a new BinaryFileAssetTask object
  85171. * @param name defines the name of the new task
  85172. * @param url defines the location of the file to load
  85173. */
  85174. function BinaryFileAssetTask(
  85175. /**
  85176. * Defines the name of the task
  85177. */
  85178. name,
  85179. /**
  85180. * Defines the location of the file to load
  85181. */
  85182. url) {
  85183. var _this = _super.call(this, name) || this;
  85184. _this.name = name;
  85185. _this.url = url;
  85186. return _this;
  85187. }
  85188. /**
  85189. * Execute the current task
  85190. * @param scene defines the scene where you want your assets to be loaded
  85191. * @param onSuccess is a callback called when the task is successfully executed
  85192. * @param onError is a callback called if an error occurs
  85193. */
  85194. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85195. var _this = this;
  85196. scene._loadFile(this.url, function (data) {
  85197. _this.data = data;
  85198. onSuccess();
  85199. }, undefined, true, true, function (request, exception) {
  85200. if (request) {
  85201. onError(request.status + " " + request.statusText, exception);
  85202. }
  85203. });
  85204. };
  85205. return BinaryFileAssetTask;
  85206. }(AbstractAssetTask));
  85207. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85208. /**
  85209. * Define a task used by {BABYLON.AssetsManager} to load images
  85210. */
  85211. var ImageAssetTask = /** @class */ (function (_super) {
  85212. __extends(ImageAssetTask, _super);
  85213. /**
  85214. * Creates a new ImageAssetTask
  85215. * @param name defines the name of the task
  85216. * @param url defines the location of the image to load
  85217. */
  85218. function ImageAssetTask(
  85219. /**
  85220. * Defines the name of the task
  85221. */
  85222. name,
  85223. /**
  85224. * Defines the location of the image to load
  85225. */
  85226. url) {
  85227. var _this = _super.call(this, name) || this;
  85228. _this.name = name;
  85229. _this.url = url;
  85230. return _this;
  85231. }
  85232. /**
  85233. * Execute the current task
  85234. * @param scene defines the scene where you want your assets to be loaded
  85235. * @param onSuccess is a callback called when the task is successfully executed
  85236. * @param onError is a callback called if an error occurs
  85237. */
  85238. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85239. var _this = this;
  85240. var img = new Image();
  85241. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85242. img.onload = function () {
  85243. _this.image = img;
  85244. onSuccess();
  85245. };
  85246. img.onerror = function (err) {
  85247. onError("Error loading image", err);
  85248. };
  85249. img.src = this.url;
  85250. };
  85251. return ImageAssetTask;
  85252. }(AbstractAssetTask));
  85253. BABYLON.ImageAssetTask = ImageAssetTask;
  85254. /**
  85255. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85256. */
  85257. var TextureAssetTask = /** @class */ (function (_super) {
  85258. __extends(TextureAssetTask, _super);
  85259. /**
  85260. * Creates a new TextureAssetTask object
  85261. * @param name defines the name of the task
  85262. * @param url defines the location of the file to load
  85263. * @param noMipmap defines if mipmap should not be generated (default is false)
  85264. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85265. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85266. */
  85267. function TextureAssetTask(
  85268. /**
  85269. * Defines the name of the task
  85270. */
  85271. name,
  85272. /**
  85273. * Defines the location of the file to load
  85274. */
  85275. url,
  85276. /**
  85277. * Defines if mipmap should not be generated (default is false)
  85278. */
  85279. noMipmap,
  85280. /**
  85281. * Defines if texture must be inverted on Y axis (default is false)
  85282. */
  85283. invertY,
  85284. /**
  85285. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85286. */
  85287. samplingMode) {
  85288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85289. var _this = _super.call(this, name) || this;
  85290. _this.name = name;
  85291. _this.url = url;
  85292. _this.noMipmap = noMipmap;
  85293. _this.invertY = invertY;
  85294. _this.samplingMode = samplingMode;
  85295. return _this;
  85296. }
  85297. /**
  85298. * Execute the current task
  85299. * @param scene defines the scene where you want your assets to be loaded
  85300. * @param onSuccess is a callback called when the task is successfully executed
  85301. * @param onError is a callback called if an error occurs
  85302. */
  85303. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85304. var onload = function () {
  85305. onSuccess();
  85306. };
  85307. var onerror = function (message, exception) {
  85308. onError(message, exception);
  85309. };
  85310. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85311. };
  85312. return TextureAssetTask;
  85313. }(AbstractAssetTask));
  85314. BABYLON.TextureAssetTask = TextureAssetTask;
  85315. /**
  85316. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85317. */
  85318. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85319. __extends(CubeTextureAssetTask, _super);
  85320. /**
  85321. * Creates a new CubeTextureAssetTask
  85322. * @param name defines the name of the task
  85323. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85324. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85325. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85326. * @param files defines the explicit list of files (undefined by default)
  85327. */
  85328. function CubeTextureAssetTask(
  85329. /**
  85330. * Defines the name of the task
  85331. */
  85332. name,
  85333. /**
  85334. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85335. */
  85336. url,
  85337. /**
  85338. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85339. */
  85340. extensions,
  85341. /**
  85342. * Defines if mipmaps should not be generated (default is false)
  85343. */
  85344. noMipmap,
  85345. /**
  85346. * Defines the explicit list of files (undefined by default)
  85347. */
  85348. files) {
  85349. var _this = _super.call(this, name) || this;
  85350. _this.name = name;
  85351. _this.url = url;
  85352. _this.extensions = extensions;
  85353. _this.noMipmap = noMipmap;
  85354. _this.files = files;
  85355. return _this;
  85356. }
  85357. /**
  85358. * Execute the current task
  85359. * @param scene defines the scene where you want your assets to be loaded
  85360. * @param onSuccess is a callback called when the task is successfully executed
  85361. * @param onError is a callback called if an error occurs
  85362. */
  85363. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85364. var onload = function () {
  85365. onSuccess();
  85366. };
  85367. var onerror = function (message, exception) {
  85368. onError(message, exception);
  85369. };
  85370. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85371. };
  85372. return CubeTextureAssetTask;
  85373. }(AbstractAssetTask));
  85374. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85375. /**
  85376. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85377. */
  85378. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85379. __extends(HDRCubeTextureAssetTask, _super);
  85380. /**
  85381. * Creates a new HDRCubeTextureAssetTask object
  85382. * @param name defines the name of the task
  85383. * @param url defines the location of the file to load
  85384. * @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.
  85385. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85386. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85387. * @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)
  85388. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85389. */
  85390. function HDRCubeTextureAssetTask(
  85391. /**
  85392. * Defines the name of the task
  85393. */
  85394. name,
  85395. /**
  85396. * Defines the location of the file to load
  85397. */
  85398. url,
  85399. /**
  85400. * 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.
  85401. */
  85402. size,
  85403. /**
  85404. * Defines if mipmaps should not be generated (default is false)
  85405. */
  85406. noMipmap,
  85407. /**
  85408. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85409. */
  85410. generateHarmonics,
  85411. /**
  85412. * 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)
  85413. */
  85414. useInGammaSpace,
  85415. /**
  85416. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85417. */
  85418. usePMREMGenerator) {
  85419. if (noMipmap === void 0) { noMipmap = false; }
  85420. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85421. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85422. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85423. var _this = _super.call(this, name) || this;
  85424. _this.name = name;
  85425. _this.url = url;
  85426. _this.size = size;
  85427. _this.noMipmap = noMipmap;
  85428. _this.generateHarmonics = generateHarmonics;
  85429. _this.useInGammaSpace = useInGammaSpace;
  85430. _this.usePMREMGenerator = usePMREMGenerator;
  85431. return _this;
  85432. }
  85433. /**
  85434. * Execute the current task
  85435. * @param scene defines the scene where you want your assets to be loaded
  85436. * @param onSuccess is a callback called when the task is successfully executed
  85437. * @param onError is a callback called if an error occurs
  85438. */
  85439. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85440. var onload = function () {
  85441. onSuccess();
  85442. };
  85443. var onerror = function (message, exception) {
  85444. onError(message, exception);
  85445. };
  85446. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85447. };
  85448. return HDRCubeTextureAssetTask;
  85449. }(AbstractAssetTask));
  85450. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85451. /**
  85452. * This class can be used to easily import assets into a scene
  85453. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85454. */
  85455. var AssetsManager = /** @class */ (function () {
  85456. /**
  85457. * Creates a new AssetsManager
  85458. * @param scene defines the scene to work on
  85459. */
  85460. function AssetsManager(scene) {
  85461. this._isLoading = false;
  85462. this._tasks = new Array();
  85463. this._waitingTasksCount = 0;
  85464. this._totalTasksCount = 0;
  85465. /**
  85466. * Observable called when all tasks are processed
  85467. */
  85468. this.onTaskSuccessObservable = new BABYLON.Observable();
  85469. /**
  85470. * Observable called when a task had an error
  85471. */
  85472. this.onTaskErrorObservable = new BABYLON.Observable();
  85473. /**
  85474. * Observable called when a task is successful
  85475. */
  85476. this.onTasksDoneObservable = new BABYLON.Observable();
  85477. /**
  85478. * Observable called when a task is done (whatever the result is)
  85479. */
  85480. this.onProgressObservable = new BABYLON.Observable();
  85481. /**
  85482. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85483. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85484. */
  85485. this.useDefaultLoadingScreen = true;
  85486. this._scene = scene;
  85487. }
  85488. /**
  85489. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85490. * @param taskName defines the name of the new task
  85491. * @param meshesNames defines the name of meshes to load
  85492. * @param rootUrl defines the root url to use to locate files
  85493. * @param sceneFilename defines the filename of the scene file
  85494. * @returns a new {BABYLON.MeshAssetTask} object
  85495. */
  85496. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85497. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85498. this._tasks.push(task);
  85499. return task;
  85500. };
  85501. /**
  85502. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85503. * @param taskName defines the name of the new task
  85504. * @param url defines the url of the file to load
  85505. * @returns a new {BABYLON.TextFileAssetTask} object
  85506. */
  85507. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85508. var task = new TextFileAssetTask(taskName, url);
  85509. this._tasks.push(task);
  85510. return task;
  85511. };
  85512. /**
  85513. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85514. * @param taskName defines the name of the new task
  85515. * @param url defines the url of the file to load
  85516. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85517. */
  85518. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85519. var task = new BinaryFileAssetTask(taskName, url);
  85520. this._tasks.push(task);
  85521. return task;
  85522. };
  85523. /**
  85524. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85525. * @param taskName defines the name of the new task
  85526. * @param url defines the url of the file to load
  85527. * @returns a new {BABYLON.ImageAssetTask} object
  85528. */
  85529. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85530. var task = new ImageAssetTask(taskName, url);
  85531. this._tasks.push(task);
  85532. return task;
  85533. };
  85534. /**
  85535. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85536. * @param taskName defines the name of the new task
  85537. * @param url defines the url of the file to load
  85538. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85539. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85540. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85541. * @returns a new {BABYLON.TextureAssetTask} object
  85542. */
  85543. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85545. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85546. this._tasks.push(task);
  85547. return task;
  85548. };
  85549. /**
  85550. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85551. * @param taskName defines the name of the new task
  85552. * @param url defines the url of the file to load
  85553. * @param extensions defines the extension to use to load the cube map (can be null)
  85554. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85555. * @param files defines the list of files to load (can be null)
  85556. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85557. */
  85558. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85559. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85560. this._tasks.push(task);
  85561. return task;
  85562. };
  85563. /**
  85564. *
  85565. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85566. * @param taskName defines the name of the new task
  85567. * @param url defines the url of the file to load
  85568. * @param size defines the size you want for the cubemap (can be null)
  85569. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85570. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85571. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85572. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85573. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85574. */
  85575. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85576. if (noMipmap === void 0) { noMipmap = false; }
  85577. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85578. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85579. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85580. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85581. this._tasks.push(task);
  85582. return task;
  85583. };
  85584. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85585. var _this = this;
  85586. this._waitingTasksCount--;
  85587. try {
  85588. if (task.taskState === AssetTaskState.DONE) {
  85589. // Let's remove successfull tasks
  85590. BABYLON.Tools.SetImmediate(function () {
  85591. var index = _this._tasks.indexOf(task);
  85592. if (index > -1) {
  85593. _this._tasks.splice(index, 1);
  85594. }
  85595. });
  85596. }
  85597. if (this.onProgress) {
  85598. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85599. }
  85600. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85601. }
  85602. catch (e) {
  85603. BABYLON.Tools.Error("Error running progress callbacks.");
  85604. console.log(e);
  85605. }
  85606. if (this._waitingTasksCount === 0) {
  85607. try {
  85608. if (this.onFinish) {
  85609. this.onFinish(this._tasks);
  85610. }
  85611. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85612. }
  85613. catch (e) {
  85614. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85615. console.log(e);
  85616. }
  85617. this._isLoading = false;
  85618. this._scene.getEngine().hideLoadingUI();
  85619. }
  85620. };
  85621. AssetsManager.prototype._runTask = function (task) {
  85622. var _this = this;
  85623. var done = function () {
  85624. try {
  85625. if (_this.onTaskSuccess) {
  85626. _this.onTaskSuccess(task);
  85627. }
  85628. _this.onTaskSuccessObservable.notifyObservers(task);
  85629. _this._decreaseWaitingTasksCount(task);
  85630. }
  85631. catch (e) {
  85632. error("Error executing task success callbacks", e);
  85633. }
  85634. };
  85635. var error = function (message, exception) {
  85636. task._setErrorObject(message, exception);
  85637. if (_this.onTaskError) {
  85638. _this.onTaskError(task);
  85639. }
  85640. _this.onTaskErrorObservable.notifyObservers(task);
  85641. _this._decreaseWaitingTasksCount(task);
  85642. };
  85643. task.run(this._scene, done, error);
  85644. };
  85645. /**
  85646. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85647. * @return the current instance of the {BABYLON.AssetsManager}
  85648. */
  85649. AssetsManager.prototype.reset = function () {
  85650. this._isLoading = false;
  85651. this._tasks = new Array();
  85652. return this;
  85653. };
  85654. /**
  85655. * Start the loading process
  85656. * @return the current instance of the {BABYLON.AssetsManager}
  85657. */
  85658. AssetsManager.prototype.load = function () {
  85659. if (this._isLoading) {
  85660. return this;
  85661. }
  85662. this._isLoading = true;
  85663. this._waitingTasksCount = this._tasks.length;
  85664. this._totalTasksCount = this._tasks.length;
  85665. if (this._waitingTasksCount === 0) {
  85666. this._isLoading = false;
  85667. if (this.onFinish) {
  85668. this.onFinish(this._tasks);
  85669. }
  85670. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85671. return this;
  85672. }
  85673. if (this.useDefaultLoadingScreen) {
  85674. this._scene.getEngine().displayLoadingUI();
  85675. }
  85676. for (var index = 0; index < this._tasks.length; index++) {
  85677. var task = this._tasks[index];
  85678. this._runTask(task);
  85679. }
  85680. return this;
  85681. };
  85682. return AssetsManager;
  85683. }());
  85684. BABYLON.AssetsManager = AssetsManager;
  85685. })(BABYLON || (BABYLON = {}));
  85686. //# sourceMappingURL=babylon.assetsManager.js.map
  85687. var BABYLON;
  85688. (function (BABYLON) {
  85689. var serializedGeometries = [];
  85690. var serializeGeometry = function (geometry, serializationGeometries) {
  85691. if (serializedGeometries[geometry.id]) {
  85692. return;
  85693. }
  85694. if (geometry.doNotSerialize) {
  85695. return;
  85696. }
  85697. if (geometry instanceof BABYLON.BoxGeometry) {
  85698. serializationGeometries.boxes.push(geometry.serialize());
  85699. }
  85700. else if (geometry instanceof BABYLON.SphereGeometry) {
  85701. serializationGeometries.spheres.push(geometry.serialize());
  85702. }
  85703. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85704. serializationGeometries.cylinders.push(geometry.serialize());
  85705. }
  85706. else if (geometry instanceof BABYLON.TorusGeometry) {
  85707. serializationGeometries.toruses.push(geometry.serialize());
  85708. }
  85709. else if (geometry instanceof BABYLON.GroundGeometry) {
  85710. serializationGeometries.grounds.push(geometry.serialize());
  85711. }
  85712. else if (geometry instanceof BABYLON.Plane) {
  85713. serializationGeometries.planes.push(geometry.serialize());
  85714. }
  85715. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85716. serializationGeometries.torusKnots.push(geometry.serialize());
  85717. }
  85718. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85719. throw new Error("Unknown primitive type");
  85720. }
  85721. else {
  85722. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85723. }
  85724. serializedGeometries[geometry.id] = true;
  85725. };
  85726. var serializeMesh = function (mesh, serializationScene) {
  85727. var serializationObject = {};
  85728. // Geometry
  85729. var geometry = mesh._geometry;
  85730. if (geometry) {
  85731. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85732. // 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
  85733. serializeGeometry(geometry, serializationScene.geometries);
  85734. }
  85735. }
  85736. // Custom
  85737. if (mesh.serialize) {
  85738. mesh.serialize(serializationObject);
  85739. }
  85740. return serializationObject;
  85741. };
  85742. var finalizeSingleMesh = function (mesh, serializationObject) {
  85743. //only works if the mesh is already loaded
  85744. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85745. //serialize material
  85746. if (mesh.material) {
  85747. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85748. serializationObject.materials = serializationObject.materials || [];
  85749. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85750. serializationObject.materials.push(mesh.material.serialize());
  85751. }
  85752. }
  85753. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85754. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85755. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85756. serializationObject.multiMaterials.push(mesh.material.serialize());
  85757. }
  85758. }
  85759. }
  85760. //serialize geometry
  85761. var geometry = mesh._geometry;
  85762. if (geometry) {
  85763. if (!serializationObject.geometries) {
  85764. serializationObject.geometries = {};
  85765. serializationObject.geometries.boxes = [];
  85766. serializationObject.geometries.spheres = [];
  85767. serializationObject.geometries.cylinders = [];
  85768. serializationObject.geometries.toruses = [];
  85769. serializationObject.geometries.grounds = [];
  85770. serializationObject.geometries.planes = [];
  85771. serializationObject.geometries.torusKnots = [];
  85772. serializationObject.geometries.vertexData = [];
  85773. }
  85774. serializeGeometry(geometry, serializationObject.geometries);
  85775. }
  85776. // Skeletons
  85777. if (mesh.skeleton) {
  85778. serializationObject.skeletons = serializationObject.skeletons || [];
  85779. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85780. }
  85781. //serialize the actual mesh
  85782. serializationObject.meshes = serializationObject.meshes || [];
  85783. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85784. }
  85785. };
  85786. var SceneSerializer = /** @class */ (function () {
  85787. function SceneSerializer() {
  85788. }
  85789. SceneSerializer.ClearCache = function () {
  85790. serializedGeometries = [];
  85791. };
  85792. SceneSerializer.Serialize = function (scene) {
  85793. var serializationObject = {};
  85794. SceneSerializer.ClearCache();
  85795. // Scene
  85796. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85797. serializationObject.autoClear = scene.autoClear;
  85798. serializationObject.clearColor = scene.clearColor.asArray();
  85799. serializationObject.ambientColor = scene.ambientColor.asArray();
  85800. serializationObject.gravity = scene.gravity.asArray();
  85801. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85802. serializationObject.workerCollisions = scene.workerCollisions;
  85803. // Fog
  85804. if (scene.fogMode && scene.fogMode !== 0) {
  85805. serializationObject.fogMode = scene.fogMode;
  85806. serializationObject.fogColor = scene.fogColor.asArray();
  85807. serializationObject.fogStart = scene.fogStart;
  85808. serializationObject.fogEnd = scene.fogEnd;
  85809. serializationObject.fogDensity = scene.fogDensity;
  85810. }
  85811. //Physics
  85812. if (scene.isPhysicsEnabled()) {
  85813. var physicEngine = scene.getPhysicsEngine();
  85814. if (physicEngine) {
  85815. serializationObject.physicsEnabled = true;
  85816. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85817. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85818. }
  85819. }
  85820. // Metadata
  85821. if (scene.metadata) {
  85822. serializationObject.metadata = scene.metadata;
  85823. }
  85824. // Morph targets
  85825. serializationObject.morphTargetManagers = [];
  85826. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85827. var abstractMesh = _a[_i];
  85828. var manager = abstractMesh.morphTargetManager;
  85829. if (manager) {
  85830. serializationObject.morphTargetManagers.push(manager.serialize());
  85831. }
  85832. }
  85833. // Lights
  85834. serializationObject.lights = [];
  85835. var index;
  85836. var light;
  85837. for (index = 0; index < scene.lights.length; index++) {
  85838. light = scene.lights[index];
  85839. if (!light.doNotSerialize) {
  85840. serializationObject.lights.push(light.serialize());
  85841. }
  85842. }
  85843. // Cameras
  85844. serializationObject.cameras = [];
  85845. for (index = 0; index < scene.cameras.length; index++) {
  85846. var camera = scene.cameras[index];
  85847. if (!camera.doNotSerialize) {
  85848. serializationObject.cameras.push(camera.serialize());
  85849. }
  85850. }
  85851. if (scene.activeCamera) {
  85852. serializationObject.activeCameraID = scene.activeCamera.id;
  85853. }
  85854. // Animations
  85855. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85856. // Materials
  85857. serializationObject.materials = [];
  85858. serializationObject.multiMaterials = [];
  85859. var material;
  85860. for (index = 0; index < scene.materials.length; index++) {
  85861. material = scene.materials[index];
  85862. if (!material.doNotSerialize) {
  85863. serializationObject.materials.push(material.serialize());
  85864. }
  85865. }
  85866. // MultiMaterials
  85867. serializationObject.multiMaterials = [];
  85868. for (index = 0; index < scene.multiMaterials.length; index++) {
  85869. var multiMaterial = scene.multiMaterials[index];
  85870. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85871. }
  85872. // Environment texture
  85873. if (scene.environmentTexture) {
  85874. serializationObject.environmentTexture = scene.environmentTexture.name;
  85875. }
  85876. // Skeletons
  85877. serializationObject.skeletons = [];
  85878. for (index = 0; index < scene.skeletons.length; index++) {
  85879. var skeleton = scene.skeletons[index];
  85880. if (!skeleton.doNotSerialize) {
  85881. serializationObject.skeletons.push(skeleton.serialize());
  85882. }
  85883. }
  85884. // Transform nodes
  85885. serializationObject.transformNodes = [];
  85886. for (index = 0; index < scene.transformNodes.length; index++) {
  85887. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85888. }
  85889. // Geometries
  85890. serializationObject.geometries = {};
  85891. serializationObject.geometries.boxes = [];
  85892. serializationObject.geometries.spheres = [];
  85893. serializationObject.geometries.cylinders = [];
  85894. serializationObject.geometries.toruses = [];
  85895. serializationObject.geometries.grounds = [];
  85896. serializationObject.geometries.planes = [];
  85897. serializationObject.geometries.torusKnots = [];
  85898. serializationObject.geometries.vertexData = [];
  85899. serializedGeometries = [];
  85900. var geometries = scene.getGeometries();
  85901. for (index = 0; index < geometries.length; index++) {
  85902. var geometry = geometries[index];
  85903. if (geometry.isReady()) {
  85904. serializeGeometry(geometry, serializationObject.geometries);
  85905. }
  85906. }
  85907. // Meshes
  85908. serializationObject.meshes = [];
  85909. for (index = 0; index < scene.meshes.length; index++) {
  85910. var abstractMesh = scene.meshes[index];
  85911. if (abstractMesh instanceof BABYLON.Mesh) {
  85912. var mesh = abstractMesh;
  85913. if (!mesh.doNotSerialize) {
  85914. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85915. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85916. }
  85917. }
  85918. }
  85919. }
  85920. // Particles Systems
  85921. serializationObject.particleSystems = [];
  85922. for (index = 0; index < scene.particleSystems.length; index++) {
  85923. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85924. }
  85925. // Lens flares
  85926. serializationObject.lensFlareSystems = [];
  85927. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85928. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85929. }
  85930. // Shadows
  85931. serializationObject.shadowGenerators = [];
  85932. for (index = 0; index < scene.lights.length; index++) {
  85933. light = scene.lights[index];
  85934. var shadowGenerator = light.getShadowGenerator();
  85935. if (shadowGenerator) {
  85936. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85937. }
  85938. }
  85939. // Action Manager
  85940. if (scene.actionManager) {
  85941. serializationObject.actions = scene.actionManager.serialize("scene");
  85942. }
  85943. // Audio
  85944. serializationObject.sounds = [];
  85945. for (index = 0; index < scene.soundTracks.length; index++) {
  85946. var soundtrack = scene.soundTracks[index];
  85947. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85948. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85949. }
  85950. }
  85951. return serializationObject;
  85952. };
  85953. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85954. if (withParents === void 0) { withParents = false; }
  85955. if (withChildren === void 0) { withChildren = false; }
  85956. var serializationObject = {};
  85957. SceneSerializer.ClearCache();
  85958. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85959. if (withParents || withChildren) {
  85960. //deliberate for loop! not for each, appended should be processed as well.
  85961. for (var i = 0; i < toSerialize.length; ++i) {
  85962. if (withChildren) {
  85963. toSerialize[i].getDescendants().forEach(function (node) {
  85964. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85965. toSerialize.push(node);
  85966. }
  85967. });
  85968. }
  85969. //make sure the array doesn't contain the object already
  85970. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85971. toSerialize.push(toSerialize[i].parent);
  85972. }
  85973. }
  85974. }
  85975. toSerialize.forEach(function (mesh) {
  85976. finalizeSingleMesh(mesh, serializationObject);
  85977. });
  85978. return serializationObject;
  85979. };
  85980. return SceneSerializer;
  85981. }());
  85982. BABYLON.SceneSerializer = SceneSerializer;
  85983. })(BABYLON || (BABYLON = {}));
  85984. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85985. var BABYLON;
  85986. (function (BABYLON) {
  85987. var ReflectionProbe = /** @class */ (function () {
  85988. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85990. var _this = this;
  85991. this.name = name;
  85992. this._viewMatrix = BABYLON.Matrix.Identity();
  85993. this._target = BABYLON.Vector3.Zero();
  85994. this._add = BABYLON.Vector3.Zero();
  85995. this._invertYAxis = false;
  85996. this.position = BABYLON.Vector3.Zero();
  85997. this._scene = scene;
  85998. this._scene.reflectionProbes.push(this);
  85999. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86000. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86001. switch (faceIndex) {
  86002. case 0:
  86003. _this._add.copyFromFloats(1, 0, 0);
  86004. break;
  86005. case 1:
  86006. _this._add.copyFromFloats(-1, 0, 0);
  86007. break;
  86008. case 2:
  86009. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86010. break;
  86011. case 3:
  86012. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86013. break;
  86014. case 4:
  86015. _this._add.copyFromFloats(0, 0, 1);
  86016. break;
  86017. case 5:
  86018. _this._add.copyFromFloats(0, 0, -1);
  86019. break;
  86020. }
  86021. if (_this._attachedMesh) {
  86022. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86023. }
  86024. _this.position.addToRef(_this._add, _this._target);
  86025. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86026. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86027. scene._forcedViewPosition = _this.position;
  86028. });
  86029. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86030. scene._forcedViewPosition = null;
  86031. scene.updateTransformMatrix(true);
  86032. });
  86033. if (scene.activeCamera) {
  86034. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86035. }
  86036. }
  86037. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86038. get: function () {
  86039. return this._renderTargetTexture.samples;
  86040. },
  86041. set: function (value) {
  86042. this._renderTargetTexture.samples = value;
  86043. },
  86044. enumerable: true,
  86045. configurable: true
  86046. });
  86047. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86048. get: function () {
  86049. return this._renderTargetTexture.refreshRate;
  86050. },
  86051. set: function (value) {
  86052. this._renderTargetTexture.refreshRate = value;
  86053. },
  86054. enumerable: true,
  86055. configurable: true
  86056. });
  86057. ReflectionProbe.prototype.getScene = function () {
  86058. return this._scene;
  86059. };
  86060. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86061. get: function () {
  86062. return this._renderTargetTexture;
  86063. },
  86064. enumerable: true,
  86065. configurable: true
  86066. });
  86067. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86068. get: function () {
  86069. return this._renderTargetTexture.renderList;
  86070. },
  86071. enumerable: true,
  86072. configurable: true
  86073. });
  86074. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86075. this._attachedMesh = mesh;
  86076. };
  86077. /**
  86078. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86079. *
  86080. * @param renderingGroupId The rendering group id corresponding to its index
  86081. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86082. */
  86083. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86084. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86085. };
  86086. ReflectionProbe.prototype.dispose = function () {
  86087. var index = this._scene.reflectionProbes.indexOf(this);
  86088. if (index !== -1) {
  86089. // Remove from the scene if found
  86090. this._scene.reflectionProbes.splice(index, 1);
  86091. }
  86092. if (this._renderTargetTexture) {
  86093. this._renderTargetTexture.dispose();
  86094. this._renderTargetTexture = null;
  86095. }
  86096. };
  86097. return ReflectionProbe;
  86098. }());
  86099. BABYLON.ReflectionProbe = ReflectionProbe;
  86100. })(BABYLON || (BABYLON = {}));
  86101. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86102. var BABYLON;
  86103. (function (BABYLON) {
  86104. var Layer = /** @class */ (function () {
  86105. function Layer(name, imgUrl, scene, isBackground, color) {
  86106. this.name = name;
  86107. this.scale = new BABYLON.Vector2(1, 1);
  86108. this.offset = new BABYLON.Vector2(0, 0);
  86109. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86110. this.layerMask = 0x0FFFFFFF;
  86111. this._vertexBuffers = {};
  86112. // Events
  86113. /**
  86114. * An event triggered when the layer is disposed.
  86115. * @type {BABYLON.Observable}
  86116. */
  86117. this.onDisposeObservable = new BABYLON.Observable();
  86118. /**
  86119. * An event triggered before rendering the scene
  86120. * @type {BABYLON.Observable}
  86121. */
  86122. this.onBeforeRenderObservable = new BABYLON.Observable();
  86123. /**
  86124. * An event triggered after rendering the scene
  86125. * @type {BABYLON.Observable}
  86126. */
  86127. this.onAfterRenderObservable = new BABYLON.Observable();
  86128. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86129. this.isBackground = isBackground === undefined ? true : isBackground;
  86130. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86131. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86132. this._scene.layers.push(this);
  86133. var engine = this._scene.getEngine();
  86134. // VBO
  86135. var vertices = [];
  86136. vertices.push(1, 1);
  86137. vertices.push(-1, 1);
  86138. vertices.push(-1, -1);
  86139. vertices.push(1, -1);
  86140. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86141. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86142. this._createIndexBuffer();
  86143. // Effects
  86144. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86145. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86146. }
  86147. Object.defineProperty(Layer.prototype, "onDispose", {
  86148. set: function (callback) {
  86149. if (this._onDisposeObserver) {
  86150. this.onDisposeObservable.remove(this._onDisposeObserver);
  86151. }
  86152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86153. },
  86154. enumerable: true,
  86155. configurable: true
  86156. });
  86157. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86158. set: function (callback) {
  86159. if (this._onBeforeRenderObserver) {
  86160. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86161. }
  86162. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86163. },
  86164. enumerable: true,
  86165. configurable: true
  86166. });
  86167. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86168. set: function (callback) {
  86169. if (this._onAfterRenderObserver) {
  86170. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86171. }
  86172. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86173. },
  86174. enumerable: true,
  86175. configurable: true
  86176. });
  86177. Layer.prototype._createIndexBuffer = function () {
  86178. var engine = this._scene.getEngine();
  86179. // Indices
  86180. var indices = [];
  86181. indices.push(0);
  86182. indices.push(1);
  86183. indices.push(2);
  86184. indices.push(0);
  86185. indices.push(2);
  86186. indices.push(3);
  86187. this._indexBuffer = engine.createIndexBuffer(indices);
  86188. };
  86189. Layer.prototype._rebuild = function () {
  86190. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86191. if (vb) {
  86192. vb._rebuild();
  86193. }
  86194. this._createIndexBuffer();
  86195. };
  86196. Layer.prototype.render = function () {
  86197. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86198. // Check
  86199. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86200. return;
  86201. var engine = this._scene.getEngine();
  86202. this.onBeforeRenderObservable.notifyObservers(this);
  86203. // Render
  86204. engine.enableEffect(currentEffect);
  86205. engine.setState(false);
  86206. // Texture
  86207. currentEffect.setTexture("textureSampler", this.texture);
  86208. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86209. // Color
  86210. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86211. // Scale / offset
  86212. currentEffect.setVector2("offset", this.offset);
  86213. currentEffect.setVector2("scale", this.scale);
  86214. // VBOs
  86215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86216. // Draw order
  86217. if (!this.alphaTest) {
  86218. engine.setAlphaMode(this.alphaBlendingMode);
  86219. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86220. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86221. }
  86222. else {
  86223. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86224. }
  86225. this.onAfterRenderObservable.notifyObservers(this);
  86226. };
  86227. Layer.prototype.dispose = function () {
  86228. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86229. if (vertexBuffer) {
  86230. vertexBuffer.dispose();
  86231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86232. }
  86233. if (this._indexBuffer) {
  86234. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86235. this._indexBuffer = null;
  86236. }
  86237. if (this.texture) {
  86238. this.texture.dispose();
  86239. this.texture = null;
  86240. }
  86241. // Remove from scene
  86242. var index = this._scene.layers.indexOf(this);
  86243. this._scene.layers.splice(index, 1);
  86244. // Callback
  86245. this.onDisposeObservable.notifyObservers(this);
  86246. this.onDisposeObservable.clear();
  86247. this.onAfterRenderObservable.clear();
  86248. this.onBeforeRenderObservable.clear();
  86249. };
  86250. return Layer;
  86251. }());
  86252. BABYLON.Layer = Layer;
  86253. })(BABYLON || (BABYLON = {}));
  86254. //# sourceMappingURL=babylon.layer.js.map
  86255. var BABYLON;
  86256. (function (BABYLON) {
  86257. var TextureTools = /** @class */ (function () {
  86258. function TextureTools() {
  86259. }
  86260. /**
  86261. * Uses the GPU to create a copy texture rescaled at a given size
  86262. * @param texture Texture to copy from
  86263. * @param width Desired width
  86264. * @param height Desired height
  86265. * @return Generated texture
  86266. */
  86267. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86268. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86269. var scene = texture.getScene();
  86270. var engine = scene.getEngine();
  86271. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86272. rtt.wrapU = texture.wrapU;
  86273. rtt.wrapV = texture.wrapV;
  86274. rtt.uOffset = texture.uOffset;
  86275. rtt.vOffset = texture.vOffset;
  86276. rtt.uScale = texture.uScale;
  86277. rtt.vScale = texture.vScale;
  86278. rtt.uAng = texture.uAng;
  86279. rtt.vAng = texture.vAng;
  86280. rtt.wAng = texture.wAng;
  86281. rtt.coordinatesIndex = texture.coordinatesIndex;
  86282. rtt.level = texture.level;
  86283. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86284. rtt._texture.isReady = false;
  86285. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86286. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86287. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86288. passPostProcess.getEffect().executeWhenCompiled(function () {
  86289. passPostProcess.onApply = function (effect) {
  86290. effect.setTexture("textureSampler", texture);
  86291. };
  86292. var internalTexture = rtt.getInternalTexture();
  86293. if (internalTexture) {
  86294. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86295. engine.unBindFramebuffer(internalTexture);
  86296. rtt.disposeFramebufferObjects();
  86297. passPostProcess.dispose();
  86298. internalTexture.isReady = true;
  86299. }
  86300. });
  86301. return rtt;
  86302. };
  86303. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86304. if (!scene._environmentBRDFTexture) {
  86305. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86306. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86307. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86308. scene._environmentBRDFTexture = texture;
  86309. }
  86310. return scene._environmentBRDFTexture;
  86311. };
  86312. 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=";
  86313. return TextureTools;
  86314. }());
  86315. BABYLON.TextureTools = TextureTools;
  86316. })(BABYLON || (BABYLON = {}));
  86317. //# sourceMappingURL=babylon.textureTools.js.map
  86318. var BABYLON;
  86319. (function (BABYLON) {
  86320. var FramingBehavior = /** @class */ (function () {
  86321. function FramingBehavior() {
  86322. this._mode = FramingBehavior.FitFrustumSidesMode;
  86323. this._radiusScale = 1.0;
  86324. this._positionScale = 0.5;
  86325. this._defaultElevation = 0.3;
  86326. this._elevationReturnTime = 1500;
  86327. this._elevationReturnWaitTime = 1000;
  86328. this._zoomStopsAnimation = false;
  86329. this._framingTime = 1500;
  86330. this._isPointerDown = false;
  86331. this._lastInteractionTime = -Infinity;
  86332. // Framing control
  86333. this._animatables = new Array();
  86334. this._betaIsAnimating = false;
  86335. }
  86336. Object.defineProperty(FramingBehavior.prototype, "name", {
  86337. get: function () {
  86338. return "Framing";
  86339. },
  86340. enumerable: true,
  86341. configurable: true
  86342. });
  86343. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86344. /**
  86345. * Gets current mode used by the behavior.
  86346. */
  86347. get: function () {
  86348. return this._mode;
  86349. },
  86350. /**
  86351. * Sets the current mode used by the behavior
  86352. */
  86353. set: function (mode) {
  86354. this._mode = mode;
  86355. },
  86356. enumerable: true,
  86357. configurable: true
  86358. });
  86359. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86360. /**
  86361. * Gets the scale applied to the radius
  86362. */
  86363. get: function () {
  86364. return this._radiusScale;
  86365. },
  86366. /**
  86367. * Sets the scale applied to the radius (1 by default)
  86368. */
  86369. set: function (radius) {
  86370. this._radiusScale = radius;
  86371. },
  86372. enumerable: true,
  86373. configurable: true
  86374. });
  86375. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86376. /**
  86377. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86378. */
  86379. get: function () {
  86380. return this._positionScale;
  86381. },
  86382. /**
  86383. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86384. */
  86385. set: function (scale) {
  86386. this._positionScale = scale;
  86387. },
  86388. enumerable: true,
  86389. configurable: true
  86390. });
  86391. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86392. /**
  86393. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86394. * behaviour is triggered, in radians.
  86395. */
  86396. get: function () {
  86397. return this._defaultElevation;
  86398. },
  86399. /**
  86400. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86401. * behaviour is triggered, in radians.
  86402. */
  86403. set: function (elevation) {
  86404. this._defaultElevation = elevation;
  86405. },
  86406. enumerable: true,
  86407. configurable: true
  86408. });
  86409. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86410. /**
  86411. * Gets the time (in milliseconds) taken to return to the default beta position.
  86412. * Negative value indicates camera should not return to default.
  86413. */
  86414. get: function () {
  86415. return this._elevationReturnTime;
  86416. },
  86417. /**
  86418. * Sets the time (in milliseconds) taken to return to the default beta position.
  86419. * Negative value indicates camera should not return to default.
  86420. */
  86421. set: function (speed) {
  86422. this._elevationReturnTime = speed;
  86423. },
  86424. enumerable: true,
  86425. configurable: true
  86426. });
  86427. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86428. /**
  86429. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86430. */
  86431. get: function () {
  86432. return this._elevationReturnWaitTime;
  86433. },
  86434. /**
  86435. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86436. */
  86437. set: function (time) {
  86438. this._elevationReturnWaitTime = time;
  86439. },
  86440. enumerable: true,
  86441. configurable: true
  86442. });
  86443. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86444. /**
  86445. * Gets the flag that indicates if user zooming should stop animation.
  86446. */
  86447. get: function () {
  86448. return this._zoomStopsAnimation;
  86449. },
  86450. /**
  86451. * Sets the flag that indicates if user zooming should stop animation.
  86452. */
  86453. set: function (flag) {
  86454. this._zoomStopsAnimation = flag;
  86455. },
  86456. enumerable: true,
  86457. configurable: true
  86458. });
  86459. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86460. /**
  86461. * Gets the transition time when framing the mesh, in milliseconds
  86462. */
  86463. get: function () {
  86464. return this._framingTime;
  86465. },
  86466. /**
  86467. * Sets the transition time when framing the mesh, in milliseconds
  86468. */
  86469. set: function (time) {
  86470. this._framingTime = time;
  86471. },
  86472. enumerable: true,
  86473. configurable: true
  86474. });
  86475. FramingBehavior.prototype.init = function () {
  86476. // Do notihng
  86477. };
  86478. FramingBehavior.prototype.attach = function (camera) {
  86479. var _this = this;
  86480. this._attachedCamera = camera;
  86481. var scene = this._attachedCamera.getScene();
  86482. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86483. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86484. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86485. _this._isPointerDown = true;
  86486. return;
  86487. }
  86488. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86489. _this._isPointerDown = false;
  86490. }
  86491. });
  86492. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86493. if (mesh) {
  86494. _this.zoomOnMesh(mesh);
  86495. }
  86496. });
  86497. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86498. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86499. _this._applyUserInteraction();
  86500. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86501. // back to the default position after a given timeout
  86502. _this._maintainCameraAboveGround();
  86503. });
  86504. };
  86505. FramingBehavior.prototype.detach = function () {
  86506. if (!this._attachedCamera) {
  86507. return;
  86508. }
  86509. var scene = this._attachedCamera.getScene();
  86510. if (this._onPrePointerObservableObserver) {
  86511. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86512. }
  86513. if (this._onAfterCheckInputsObserver) {
  86514. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86515. }
  86516. if (this._onMeshTargetChangedObserver) {
  86517. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86518. }
  86519. this._attachedCamera = null;
  86520. };
  86521. /**
  86522. * Targets the given mesh and updates zoom level accordingly.
  86523. * @param mesh The mesh to target.
  86524. * @param radius Optional. If a cached radius position already exists, overrides default.
  86525. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86526. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86527. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86528. */
  86529. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86530. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86531. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86532. mesh.computeWorldMatrix(true);
  86533. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86534. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86535. };
  86536. /**
  86537. * Targets the given mesh with its children and updates zoom level accordingly.
  86538. * @param mesh The mesh to target.
  86539. * @param radius Optional. If a cached radius position already exists, overrides default.
  86540. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86541. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86542. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86543. */
  86544. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86545. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86546. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86547. mesh.computeWorldMatrix(true);
  86548. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86549. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86550. };
  86551. /**
  86552. * Targets the given meshes with their children and updates zoom level accordingly.
  86553. * @param meshes The mesh to target.
  86554. * @param radius Optional. If a cached radius position already exists, overrides default.
  86555. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86556. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86557. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86558. */
  86559. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86560. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86561. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86562. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86563. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86564. for (var i = 0; i < meshes.length; i++) {
  86565. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86566. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86567. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86568. }
  86569. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86570. };
  86571. /**
  86572. * Targets the given mesh and updates zoom level accordingly.
  86573. * @param mesh The mesh to target.
  86574. * @param radius Optional. If a cached radius position already exists, overrides default.
  86575. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86576. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86577. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86578. */
  86579. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86580. var _this = this;
  86581. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86582. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86583. var zoomTarget;
  86584. if (!this._attachedCamera) {
  86585. return;
  86586. }
  86587. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86588. var bottom = minimumWorld.y;
  86589. var top = maximumWorld.y;
  86590. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86591. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86592. if (focusOnOriginXZ) {
  86593. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86594. }
  86595. else {
  86596. var centerWorld = minimumWorld.add(radiusWorld);
  86597. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86598. }
  86599. if (!this._vectorTransition) {
  86600. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86601. }
  86602. this._betaIsAnimating = true;
  86603. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86604. if (animatable) {
  86605. this._animatables.push(animatable);
  86606. }
  86607. // sets the radius and lower radius bounds
  86608. // Small delta ensures camera is not always at lower zoom limit.
  86609. var radius = 0;
  86610. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86611. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86612. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86613. radius = position;
  86614. }
  86615. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86616. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86617. if (this._attachedCamera.lowerRadiusLimit === null) {
  86618. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86619. }
  86620. }
  86621. // Set sensibilities
  86622. var extend = maximumWorld.subtract(minimumWorld).length();
  86623. this._attachedCamera.panningSensibility = 5000 / extend;
  86624. this._attachedCamera.wheelPrecision = 100 / radius;
  86625. // transition to new radius
  86626. if (!this._radiusTransition) {
  86627. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86628. }
  86629. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86630. if (onAnimationEnd) {
  86631. onAnimationEnd();
  86632. }
  86633. if (_this._attachedCamera) {
  86634. _this._attachedCamera.storeState();
  86635. }
  86636. });
  86637. if (animatable) {
  86638. this._animatables.push(animatable);
  86639. }
  86640. };
  86641. /**
  86642. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86643. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86644. * frustum width.
  86645. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86646. * to fully enclose the mesh in the viewing frustum.
  86647. */
  86648. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86649. var size = maximumWorld.subtract(minimumWorld);
  86650. var boxVectorGlobalDiagonal = size.length();
  86651. var frustumSlope = this._getFrustumSlope();
  86652. // Formula for setting distance
  86653. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86654. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86655. // Horizon distance
  86656. var radius = radiusWithoutFraming * this._radiusScale;
  86657. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86658. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86659. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86660. var camera = this._attachedCamera;
  86661. if (!camera) {
  86662. return 0;
  86663. }
  86664. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86665. // Don't exceed the requested limit
  86666. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86667. }
  86668. // Don't exceed the upper radius limit
  86669. if (camera.upperRadiusLimit) {
  86670. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86671. }
  86672. return distance;
  86673. };
  86674. /**
  86675. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86676. * is automatically returned to its default position (expected to be above ground plane).
  86677. */
  86678. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86679. var _this = this;
  86680. if (this._elevationReturnTime < 0) {
  86681. return;
  86682. }
  86683. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86684. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86685. var limitBeta = Math.PI * 0.5;
  86686. // Bring the camera back up if below the ground plane
  86687. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86688. this._betaIsAnimating = true;
  86689. //Transition to new position
  86690. this.stopAllAnimations();
  86691. if (!this._betaTransition) {
  86692. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86693. }
  86694. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86695. _this._clearAnimationLocks();
  86696. _this.stopAllAnimations();
  86697. });
  86698. if (animatabe) {
  86699. this._animatables.push(animatabe);
  86700. }
  86701. }
  86702. };
  86703. /**
  86704. * Returns the frustum slope based on the canvas ratio and camera FOV
  86705. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86706. */
  86707. FramingBehavior.prototype._getFrustumSlope = function () {
  86708. // Calculate the viewport ratio
  86709. // Aspect Ratio is Height/Width.
  86710. var camera = this._attachedCamera;
  86711. if (!camera) {
  86712. return BABYLON.Vector2.Zero();
  86713. }
  86714. var engine = camera.getScene().getEngine();
  86715. var aspectRatio = engine.getAspectRatio(camera);
  86716. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86717. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86718. var frustumSlopeY = Math.tan(camera.fov / 2);
  86719. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86720. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86721. // along the forward vector.
  86722. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86723. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86724. };
  86725. /**
  86726. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86727. */
  86728. FramingBehavior.prototype._clearAnimationLocks = function () {
  86729. this._betaIsAnimating = false;
  86730. };
  86731. /**
  86732. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86733. */
  86734. FramingBehavior.prototype._applyUserInteraction = function () {
  86735. if (this.isUserIsMoving) {
  86736. this._lastInteractionTime = BABYLON.Tools.Now;
  86737. this.stopAllAnimations();
  86738. this._clearAnimationLocks();
  86739. }
  86740. };
  86741. /**
  86742. * Stops and removes all animations that have been applied to the camera
  86743. */
  86744. FramingBehavior.prototype.stopAllAnimations = function () {
  86745. if (this._attachedCamera) {
  86746. this._attachedCamera.animations = [];
  86747. }
  86748. while (this._animatables.length) {
  86749. if (this._animatables[0]) {
  86750. this._animatables[0].onAnimationEnd = null;
  86751. this._animatables[0].stop();
  86752. }
  86753. this._animatables.shift();
  86754. }
  86755. };
  86756. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86757. /**
  86758. * Gets a value indicating if the user is moving the camera
  86759. */
  86760. get: function () {
  86761. if (!this._attachedCamera) {
  86762. return false;
  86763. }
  86764. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86765. this._attachedCamera.inertialBetaOffset !== 0 ||
  86766. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86767. this._attachedCamera.inertialPanningX !== 0 ||
  86768. this._attachedCamera.inertialPanningY !== 0 ||
  86769. this._isPointerDown;
  86770. },
  86771. enumerable: true,
  86772. configurable: true
  86773. });
  86774. /**
  86775. * The easing function used by animations
  86776. */
  86777. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86778. /**
  86779. * The easing mode used by animations
  86780. */
  86781. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86782. // Statics
  86783. /**
  86784. * The camera can move all the way towards the mesh.
  86785. */
  86786. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86787. /**
  86788. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86789. */
  86790. FramingBehavior.FitFrustumSidesMode = 1;
  86791. return FramingBehavior;
  86792. }());
  86793. BABYLON.FramingBehavior = FramingBehavior;
  86794. })(BABYLON || (BABYLON = {}));
  86795. //# sourceMappingURL=babylon.framingBehavior.js.map
  86796. var BABYLON;
  86797. (function (BABYLON) {
  86798. /**
  86799. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86800. */
  86801. var BouncingBehavior = /** @class */ (function () {
  86802. function BouncingBehavior() {
  86803. /**
  86804. * The duration of the animation, in milliseconds
  86805. */
  86806. this.transitionDuration = 450;
  86807. /**
  86808. * Length of the distance animated by the transition when lower radius is reached
  86809. */
  86810. this.lowerRadiusTransitionRange = 2;
  86811. /**
  86812. * Length of the distance animated by the transition when upper radius is reached
  86813. */
  86814. this.upperRadiusTransitionRange = -2;
  86815. this._autoTransitionRange = false;
  86816. // Animations
  86817. this._radiusIsAnimating = false;
  86818. this._radiusBounceTransition = null;
  86819. this._animatables = new Array();
  86820. }
  86821. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86822. get: function () {
  86823. return "Bouncing";
  86824. },
  86825. enumerable: true,
  86826. configurable: true
  86827. });
  86828. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86829. /**
  86830. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86831. */
  86832. get: function () {
  86833. return this._autoTransitionRange;
  86834. },
  86835. /**
  86836. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86837. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86838. */
  86839. set: function (value) {
  86840. var _this = this;
  86841. if (this._autoTransitionRange === value) {
  86842. return;
  86843. }
  86844. this._autoTransitionRange = value;
  86845. var camera = this._attachedCamera;
  86846. if (!camera) {
  86847. return;
  86848. }
  86849. if (value) {
  86850. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86851. if (!mesh) {
  86852. return;
  86853. }
  86854. mesh.computeWorldMatrix(true);
  86855. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86856. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86857. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86858. });
  86859. }
  86860. else if (this._onMeshTargetChangedObserver) {
  86861. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86862. }
  86863. },
  86864. enumerable: true,
  86865. configurable: true
  86866. });
  86867. BouncingBehavior.prototype.init = function () {
  86868. // Do notihng
  86869. };
  86870. BouncingBehavior.prototype.attach = function (camera) {
  86871. var _this = this;
  86872. this._attachedCamera = camera;
  86873. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86874. if (!_this._attachedCamera) {
  86875. return;
  86876. }
  86877. // Add the bounce animation to the lower radius limit
  86878. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86879. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86880. }
  86881. // Add the bounce animation to the upper radius limit
  86882. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86883. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86884. }
  86885. });
  86886. };
  86887. BouncingBehavior.prototype.detach = function () {
  86888. if (!this._attachedCamera) {
  86889. return;
  86890. }
  86891. if (this._onAfterCheckInputsObserver) {
  86892. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86893. }
  86894. if (this._onMeshTargetChangedObserver) {
  86895. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86896. }
  86897. this._attachedCamera = null;
  86898. };
  86899. /**
  86900. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86901. * @param radiusLimit The limit to check against.
  86902. * @return Bool to indicate if at limit.
  86903. */
  86904. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86905. if (!this._attachedCamera) {
  86906. return false;
  86907. }
  86908. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86909. return true;
  86910. }
  86911. return false;
  86912. };
  86913. /**
  86914. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86915. * @param radiusDelta The delta by which to animate to. Can be negative.
  86916. */
  86917. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86918. var _this = this;
  86919. if (!this._attachedCamera) {
  86920. return;
  86921. }
  86922. if (!this._radiusBounceTransition) {
  86923. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86924. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86925. }
  86926. // Prevent zoom until bounce has completed
  86927. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86928. this._attachedCamera.wheelPrecision = Infinity;
  86929. this._attachedCamera.inertialRadiusOffset = 0;
  86930. // Animate to the radius limit
  86931. this.stopAllAnimations();
  86932. this._radiusIsAnimating = true;
  86933. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86934. if (animatable) {
  86935. this._animatables.push(animatable);
  86936. }
  86937. };
  86938. /**
  86939. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86940. */
  86941. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86942. this._radiusIsAnimating = false;
  86943. if (this._attachedCamera) {
  86944. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86945. }
  86946. };
  86947. /**
  86948. * Stops and removes all animations that have been applied to the camera
  86949. */
  86950. BouncingBehavior.prototype.stopAllAnimations = function () {
  86951. if (this._attachedCamera) {
  86952. this._attachedCamera.animations = [];
  86953. }
  86954. while (this._animatables.length) {
  86955. this._animatables[0].onAnimationEnd = null;
  86956. this._animatables[0].stop();
  86957. this._animatables.shift();
  86958. }
  86959. };
  86960. /**
  86961. * The easing function used by animations
  86962. */
  86963. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86964. /**
  86965. * The easing mode used by animations
  86966. */
  86967. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86968. return BouncingBehavior;
  86969. }());
  86970. BABYLON.BouncingBehavior = BouncingBehavior;
  86971. })(BABYLON || (BABYLON = {}));
  86972. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86973. var BABYLON;
  86974. (function (BABYLON) {
  86975. var AutoRotationBehavior = /** @class */ (function () {
  86976. function AutoRotationBehavior() {
  86977. this._zoomStopsAnimation = false;
  86978. this._idleRotationSpeed = 0.05;
  86979. this._idleRotationWaitTime = 2000;
  86980. this._idleRotationSpinupTime = 2000;
  86981. this._isPointerDown = false;
  86982. this._lastFrameTime = null;
  86983. this._lastInteractionTime = -Infinity;
  86984. this._cameraRotationSpeed = 0;
  86985. this._lastFrameRadius = 0;
  86986. }
  86987. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86988. get: function () {
  86989. return "AutoRotation";
  86990. },
  86991. enumerable: true,
  86992. configurable: true
  86993. });
  86994. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86995. /**
  86996. * Gets the flag that indicates if user zooming should stop animation.
  86997. */
  86998. get: function () {
  86999. return this._zoomStopsAnimation;
  87000. },
  87001. /**
  87002. * Sets the flag that indicates if user zooming should stop animation.
  87003. */
  87004. set: function (flag) {
  87005. this._zoomStopsAnimation = flag;
  87006. },
  87007. enumerable: true,
  87008. configurable: true
  87009. });
  87010. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87011. /**
  87012. * Gets the default speed at which the camera rotates around the model.
  87013. */
  87014. get: function () {
  87015. return this._idleRotationSpeed;
  87016. },
  87017. /**
  87018. * Sets the default speed at which the camera rotates around the model.
  87019. */
  87020. set: function (speed) {
  87021. this._idleRotationSpeed = speed;
  87022. },
  87023. enumerable: true,
  87024. configurable: true
  87025. });
  87026. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87027. /**
  87028. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87029. */
  87030. get: function () {
  87031. return this._idleRotationWaitTime;
  87032. },
  87033. /**
  87034. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87035. */
  87036. set: function (time) {
  87037. this._idleRotationWaitTime = time;
  87038. },
  87039. enumerable: true,
  87040. configurable: true
  87041. });
  87042. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87043. /**
  87044. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87045. */
  87046. get: function () {
  87047. return this._idleRotationSpinupTime;
  87048. },
  87049. /**
  87050. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87051. */
  87052. set: function (time) {
  87053. this._idleRotationSpinupTime = time;
  87054. },
  87055. enumerable: true,
  87056. configurable: true
  87057. });
  87058. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87059. /**
  87060. * Gets a value indicating if the camera is currently rotating because of this behavior
  87061. */
  87062. get: function () {
  87063. return Math.abs(this._cameraRotationSpeed) > 0;
  87064. },
  87065. enumerable: true,
  87066. configurable: true
  87067. });
  87068. AutoRotationBehavior.prototype.init = function () {
  87069. // Do notihng
  87070. };
  87071. AutoRotationBehavior.prototype.attach = function (camera) {
  87072. var _this = this;
  87073. this._attachedCamera = camera;
  87074. var scene = this._attachedCamera.getScene();
  87075. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87076. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87077. _this._isPointerDown = true;
  87078. return;
  87079. }
  87080. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87081. _this._isPointerDown = false;
  87082. }
  87083. });
  87084. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87085. var now = BABYLON.Tools.Now;
  87086. var dt = 0;
  87087. if (_this._lastFrameTime != null) {
  87088. dt = now - _this._lastFrameTime;
  87089. }
  87090. _this._lastFrameTime = now;
  87091. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87092. _this._applyUserInteraction();
  87093. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87094. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87095. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87096. // Step camera rotation by rotation speed
  87097. if (_this._attachedCamera) {
  87098. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87099. }
  87100. });
  87101. };
  87102. AutoRotationBehavior.prototype.detach = function () {
  87103. if (!this._attachedCamera) {
  87104. return;
  87105. }
  87106. var scene = this._attachedCamera.getScene();
  87107. if (this._onPrePointerObservableObserver) {
  87108. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87109. }
  87110. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87111. this._attachedCamera = null;
  87112. };
  87113. /**
  87114. * Returns true if user is scrolling.
  87115. * @return true if user is scrolling.
  87116. */
  87117. AutoRotationBehavior.prototype._userIsZooming = function () {
  87118. if (!this._attachedCamera) {
  87119. return false;
  87120. }
  87121. return this._attachedCamera.inertialRadiusOffset !== 0;
  87122. };
  87123. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87124. if (!this._attachedCamera) {
  87125. return false;
  87126. }
  87127. var zoomHasHitLimit = false;
  87128. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87129. zoomHasHitLimit = true;
  87130. }
  87131. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87132. this._lastFrameRadius = this._attachedCamera.radius;
  87133. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87134. };
  87135. /**
  87136. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87137. */
  87138. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87139. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87140. this._lastInteractionTime = BABYLON.Tools.Now;
  87141. }
  87142. };
  87143. // Tools
  87144. AutoRotationBehavior.prototype._userIsMoving = function () {
  87145. if (!this._attachedCamera) {
  87146. return false;
  87147. }
  87148. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87149. this._attachedCamera.inertialBetaOffset !== 0 ||
  87150. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87151. this._attachedCamera.inertialPanningX !== 0 ||
  87152. this._attachedCamera.inertialPanningY !== 0 ||
  87153. this._isPointerDown;
  87154. };
  87155. return AutoRotationBehavior;
  87156. }());
  87157. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87158. })(BABYLON || (BABYLON = {}));
  87159. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87160. var BABYLON;
  87161. (function (BABYLON) {
  87162. /**
  87163. * This class can be used to get instrumentation data from a Babylon engine
  87164. */
  87165. var EngineInstrumentation = /** @class */ (function () {
  87166. function EngineInstrumentation(engine) {
  87167. this.engine = engine;
  87168. this._captureGPUFrameTime = false;
  87169. this._gpuFrameTime = new BABYLON.PerfCounter();
  87170. this._captureShaderCompilationTime = false;
  87171. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87172. // Observers
  87173. this._onBeginFrameObserver = null;
  87174. this._onEndFrameObserver = null;
  87175. this._onBeforeShaderCompilationObserver = null;
  87176. this._onAfterShaderCompilationObserver = null;
  87177. }
  87178. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87179. // Properties
  87180. /**
  87181. * Gets the perf counter used for GPU frame time
  87182. */
  87183. get: function () {
  87184. return this._gpuFrameTime;
  87185. },
  87186. enumerable: true,
  87187. configurable: true
  87188. });
  87189. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87190. /**
  87191. * Gets the GPU frame time capture status
  87192. */
  87193. get: function () {
  87194. return this._captureGPUFrameTime;
  87195. },
  87196. /**
  87197. * Enable or disable the GPU frame time capture
  87198. */
  87199. set: function (value) {
  87200. var _this = this;
  87201. if (value === this._captureGPUFrameTime) {
  87202. return;
  87203. }
  87204. this._captureGPUFrameTime = value;
  87205. if (value) {
  87206. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87207. if (!_this._gpuFrameTimeToken) {
  87208. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87209. }
  87210. });
  87211. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87212. if (!_this._gpuFrameTimeToken) {
  87213. return;
  87214. }
  87215. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87216. if (time > -1) {
  87217. _this._gpuFrameTimeToken = null;
  87218. _this._gpuFrameTime.fetchNewFrame();
  87219. _this._gpuFrameTime.addCount(time, true);
  87220. }
  87221. });
  87222. }
  87223. else {
  87224. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87225. this._onBeginFrameObserver = null;
  87226. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87227. this._onEndFrameObserver = null;
  87228. }
  87229. },
  87230. enumerable: true,
  87231. configurable: true
  87232. });
  87233. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87234. /**
  87235. * Gets the perf counter used for shader compilation time
  87236. */
  87237. get: function () {
  87238. return this._shaderCompilationTime;
  87239. },
  87240. enumerable: true,
  87241. configurable: true
  87242. });
  87243. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87244. /**
  87245. * Gets the shader compilation time capture status
  87246. */
  87247. get: function () {
  87248. return this._captureShaderCompilationTime;
  87249. },
  87250. /**
  87251. * Enable or disable the shader compilation time capture
  87252. */
  87253. set: function (value) {
  87254. var _this = this;
  87255. if (value === this._captureShaderCompilationTime) {
  87256. return;
  87257. }
  87258. this._captureShaderCompilationTime = value;
  87259. if (value) {
  87260. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87261. _this._shaderCompilationTime.fetchNewFrame();
  87262. _this._shaderCompilationTime.beginMonitoring();
  87263. });
  87264. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87265. _this._shaderCompilationTime.endMonitoring();
  87266. });
  87267. }
  87268. else {
  87269. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87270. this._onBeforeShaderCompilationObserver = null;
  87271. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87272. this._onAfterShaderCompilationObserver = null;
  87273. }
  87274. },
  87275. enumerable: true,
  87276. configurable: true
  87277. });
  87278. EngineInstrumentation.prototype.dispose = function () {
  87279. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87280. this._onBeginFrameObserver = null;
  87281. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87282. this._onEndFrameObserver = null;
  87283. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87284. this._onBeforeShaderCompilationObserver = null;
  87285. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87286. this._onAfterShaderCompilationObserver = null;
  87287. this.engine = null;
  87288. };
  87289. return EngineInstrumentation;
  87290. }());
  87291. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87292. })(BABYLON || (BABYLON = {}));
  87293. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87294. var BABYLON;
  87295. (function (BABYLON) {
  87296. /**
  87297. * This class can be used to get instrumentation data from a Babylon engine
  87298. */
  87299. var SceneInstrumentation = /** @class */ (function () {
  87300. function SceneInstrumentation(scene) {
  87301. var _this = this;
  87302. this.scene = scene;
  87303. this._captureActiveMeshesEvaluationTime = false;
  87304. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87305. this._captureRenderTargetsRenderTime = false;
  87306. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87307. this._captureFrameTime = false;
  87308. this._frameTime = new BABYLON.PerfCounter();
  87309. this._captureRenderTime = false;
  87310. this._renderTime = new BABYLON.PerfCounter();
  87311. this._captureInterFrameTime = false;
  87312. this._interFrameTime = new BABYLON.PerfCounter();
  87313. this._captureParticlesRenderTime = false;
  87314. this._particlesRenderTime = new BABYLON.PerfCounter();
  87315. this._captureSpritesRenderTime = false;
  87316. this._spritesRenderTime = new BABYLON.PerfCounter();
  87317. this._capturePhysicsTime = false;
  87318. this._physicsTime = new BABYLON.PerfCounter();
  87319. this._captureAnimationsTime = false;
  87320. this._animationsTime = new BABYLON.PerfCounter();
  87321. // Observers
  87322. this._onBeforeActiveMeshesEvaluationObserver = null;
  87323. this._onAfterActiveMeshesEvaluationObserver = null;
  87324. this._onBeforeRenderTargetsRenderObserver = null;
  87325. this._onAfterRenderTargetsRenderObserver = null;
  87326. this._onAfterRenderObserver = null;
  87327. this._onBeforeDrawPhaseObserver = null;
  87328. this._onAfterDrawPhaseObserver = null;
  87329. this._onBeforeAnimationsObserver = null;
  87330. this._onBeforeParticlesRenderingObserver = null;
  87331. this._onAfterParticlesRenderingObserver = null;
  87332. this._onBeforeSpritesRenderingObserver = null;
  87333. this._onAfterSpritesRenderingObserver = null;
  87334. this._onBeforePhysicsObserver = null;
  87335. this._onAfterPhysicsObserver = null;
  87336. this._onAfterAnimationsObserver = null;
  87337. // Before render
  87338. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87339. if (_this._captureActiveMeshesEvaluationTime) {
  87340. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87341. }
  87342. if (_this._captureRenderTargetsRenderTime) {
  87343. _this._renderTargetsRenderTime.fetchNewFrame();
  87344. }
  87345. if (_this._captureFrameTime) {
  87346. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87347. _this._frameTime.beginMonitoring();
  87348. }
  87349. if (_this._captureInterFrameTime) {
  87350. _this._interFrameTime.endMonitoring();
  87351. }
  87352. if (_this._captureParticlesRenderTime) {
  87353. _this._particlesRenderTime.fetchNewFrame();
  87354. }
  87355. if (_this._captureSpritesRenderTime) {
  87356. _this._spritesRenderTime.fetchNewFrame();
  87357. }
  87358. if (_this._captureAnimationsTime) {
  87359. _this._animationsTime.beginMonitoring();
  87360. }
  87361. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87362. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87363. });
  87364. // After render
  87365. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87366. if (_this._captureFrameTime) {
  87367. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87368. _this._frameTime.endMonitoring();
  87369. }
  87370. if (_this._captureRenderTime) {
  87371. _this._renderTime.endMonitoring(false);
  87372. }
  87373. if (_this._captureInterFrameTime) {
  87374. _this._interFrameTime.beginMonitoring();
  87375. }
  87376. });
  87377. }
  87378. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87379. // Properties
  87380. /**
  87381. * Gets the perf counter used for active meshes evaluation time
  87382. */
  87383. get: function () {
  87384. return this._activeMeshesEvaluationTime;
  87385. },
  87386. enumerable: true,
  87387. configurable: true
  87388. });
  87389. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87390. /**
  87391. * Gets the active meshes evaluation time capture status
  87392. */
  87393. get: function () {
  87394. return this._captureActiveMeshesEvaluationTime;
  87395. },
  87396. /**
  87397. * Enable or disable the active meshes evaluation time capture
  87398. */
  87399. set: function (value) {
  87400. var _this = this;
  87401. if (value === this._captureActiveMeshesEvaluationTime) {
  87402. return;
  87403. }
  87404. this._captureActiveMeshesEvaluationTime = value;
  87405. if (value) {
  87406. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87407. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87408. _this._activeMeshesEvaluationTime.beginMonitoring();
  87409. });
  87410. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87411. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87412. _this._activeMeshesEvaluationTime.endMonitoring();
  87413. });
  87414. }
  87415. else {
  87416. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87417. this._onBeforeActiveMeshesEvaluationObserver = null;
  87418. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87419. this._onAfterActiveMeshesEvaluationObserver = null;
  87420. }
  87421. },
  87422. enumerable: true,
  87423. configurable: true
  87424. });
  87425. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87426. /**
  87427. * Gets the perf counter used for render targets render time
  87428. */
  87429. get: function () {
  87430. return this._renderTargetsRenderTime;
  87431. },
  87432. enumerable: true,
  87433. configurable: true
  87434. });
  87435. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87436. /**
  87437. * Gets the render targets render time capture status
  87438. */
  87439. get: function () {
  87440. return this._captureRenderTargetsRenderTime;
  87441. },
  87442. /**
  87443. * Enable or disable the render targets render time capture
  87444. */
  87445. set: function (value) {
  87446. var _this = this;
  87447. if (value === this._captureRenderTargetsRenderTime) {
  87448. return;
  87449. }
  87450. this._captureRenderTargetsRenderTime = value;
  87451. if (value) {
  87452. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87453. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87454. _this._renderTargetsRenderTime.beginMonitoring();
  87455. });
  87456. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87457. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87458. _this._renderTargetsRenderTime.endMonitoring(false);
  87459. });
  87460. }
  87461. else {
  87462. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87463. this._onBeforeRenderTargetsRenderObserver = null;
  87464. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87465. this._onAfterRenderTargetsRenderObserver = null;
  87466. }
  87467. },
  87468. enumerable: true,
  87469. configurable: true
  87470. });
  87471. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87472. /**
  87473. * Gets the perf counter used for particles render time
  87474. */
  87475. get: function () {
  87476. return this._particlesRenderTime;
  87477. },
  87478. enumerable: true,
  87479. configurable: true
  87480. });
  87481. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87482. /**
  87483. * Gets the particles render time capture status
  87484. */
  87485. get: function () {
  87486. return this._captureParticlesRenderTime;
  87487. },
  87488. /**
  87489. * Enable or disable the particles render time capture
  87490. */
  87491. set: function (value) {
  87492. var _this = this;
  87493. if (value === this._captureParticlesRenderTime) {
  87494. return;
  87495. }
  87496. this._captureParticlesRenderTime = value;
  87497. if (value) {
  87498. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87499. BABYLON.Tools.StartPerformanceCounter("Particles");
  87500. _this._particlesRenderTime.beginMonitoring();
  87501. });
  87502. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87503. BABYLON.Tools.EndPerformanceCounter("Particles");
  87504. _this._particlesRenderTime.endMonitoring(false);
  87505. });
  87506. }
  87507. else {
  87508. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87509. this._onBeforeParticlesRenderingObserver = null;
  87510. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87511. this._onAfterParticlesRenderingObserver = null;
  87512. }
  87513. },
  87514. enumerable: true,
  87515. configurable: true
  87516. });
  87517. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87518. /**
  87519. * Gets the perf counter used for sprites render time
  87520. */
  87521. get: function () {
  87522. return this._spritesRenderTime;
  87523. },
  87524. enumerable: true,
  87525. configurable: true
  87526. });
  87527. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87528. /**
  87529. * Gets the sprites render time capture status
  87530. */
  87531. get: function () {
  87532. return this._captureSpritesRenderTime;
  87533. },
  87534. /**
  87535. * Enable or disable the sprites render time capture
  87536. */
  87537. set: function (value) {
  87538. var _this = this;
  87539. if (value === this._captureSpritesRenderTime) {
  87540. return;
  87541. }
  87542. this._captureSpritesRenderTime = value;
  87543. if (value) {
  87544. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87545. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87546. _this._spritesRenderTime.beginMonitoring();
  87547. });
  87548. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87549. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87550. _this._spritesRenderTime.endMonitoring(false);
  87551. });
  87552. }
  87553. else {
  87554. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87555. this._onBeforeSpritesRenderingObserver = null;
  87556. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87557. this._onAfterSpritesRenderingObserver = null;
  87558. }
  87559. },
  87560. enumerable: true,
  87561. configurable: true
  87562. });
  87563. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87564. /**
  87565. * Gets the perf counter used for physics time
  87566. */
  87567. get: function () {
  87568. return this._physicsTime;
  87569. },
  87570. enumerable: true,
  87571. configurable: true
  87572. });
  87573. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87574. /**
  87575. * Gets the physics time capture status
  87576. */
  87577. get: function () {
  87578. return this._capturePhysicsTime;
  87579. },
  87580. /**
  87581. * Enable or disable the physics time capture
  87582. */
  87583. set: function (value) {
  87584. var _this = this;
  87585. if (value === this._capturePhysicsTime) {
  87586. return;
  87587. }
  87588. this._capturePhysicsTime = value;
  87589. if (value) {
  87590. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87591. BABYLON.Tools.StartPerformanceCounter("Physics");
  87592. _this._physicsTime.beginMonitoring();
  87593. });
  87594. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87595. BABYLON.Tools.EndPerformanceCounter("Physics");
  87596. _this._physicsTime.endMonitoring();
  87597. });
  87598. }
  87599. else {
  87600. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87601. this._onBeforePhysicsObserver = null;
  87602. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87603. this._onAfterPhysicsObserver = null;
  87604. }
  87605. },
  87606. enumerable: true,
  87607. configurable: true
  87608. });
  87609. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87610. /**
  87611. * Gets the perf counter used for animations time
  87612. */
  87613. get: function () {
  87614. return this._animationsTime;
  87615. },
  87616. enumerable: true,
  87617. configurable: true
  87618. });
  87619. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87620. /**
  87621. * Gets the animations time capture status
  87622. */
  87623. get: function () {
  87624. return this._captureAnimationsTime;
  87625. },
  87626. /**
  87627. * Enable or disable the animations time capture
  87628. */
  87629. set: function (value) {
  87630. var _this = this;
  87631. if (value === this._captureAnimationsTime) {
  87632. return;
  87633. }
  87634. this._captureAnimationsTime = value;
  87635. if (value) {
  87636. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87637. _this._animationsTime.endMonitoring();
  87638. });
  87639. }
  87640. else {
  87641. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87642. this._onAfterAnimationsObserver = null;
  87643. }
  87644. },
  87645. enumerable: true,
  87646. configurable: true
  87647. });
  87648. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87649. /**
  87650. * Gets the perf counter used for frame time capture
  87651. */
  87652. get: function () {
  87653. return this._frameTime;
  87654. },
  87655. enumerable: true,
  87656. configurable: true
  87657. });
  87658. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87659. /**
  87660. * Gets the frame time capture status
  87661. */
  87662. get: function () {
  87663. return this._captureFrameTime;
  87664. },
  87665. /**
  87666. * Enable or disable the frame time capture
  87667. */
  87668. set: function (value) {
  87669. this._captureFrameTime = value;
  87670. },
  87671. enumerable: true,
  87672. configurable: true
  87673. });
  87674. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87675. /**
  87676. * Gets the perf counter used for inter-frames time capture
  87677. */
  87678. get: function () {
  87679. return this._interFrameTime;
  87680. },
  87681. enumerable: true,
  87682. configurable: true
  87683. });
  87684. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87685. /**
  87686. * Gets the inter-frames time capture status
  87687. */
  87688. get: function () {
  87689. return this._captureInterFrameTime;
  87690. },
  87691. /**
  87692. * Enable or disable the inter-frames time capture
  87693. */
  87694. set: function (value) {
  87695. this._captureInterFrameTime = value;
  87696. },
  87697. enumerable: true,
  87698. configurable: true
  87699. });
  87700. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87701. /**
  87702. * Gets the perf counter used for render time capture
  87703. */
  87704. get: function () {
  87705. return this._renderTime;
  87706. },
  87707. enumerable: true,
  87708. configurable: true
  87709. });
  87710. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87711. /**
  87712. * Gets the render time capture status
  87713. */
  87714. get: function () {
  87715. return this._captureRenderTime;
  87716. },
  87717. /**
  87718. * Enable or disable the render time capture
  87719. */
  87720. set: function (value) {
  87721. var _this = this;
  87722. if (value === this._captureRenderTime) {
  87723. return;
  87724. }
  87725. this._captureRenderTime = value;
  87726. if (value) {
  87727. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87728. _this._renderTime.beginMonitoring();
  87729. BABYLON.Tools.StartPerformanceCounter("Main render");
  87730. });
  87731. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87732. _this._renderTime.endMonitoring(false);
  87733. BABYLON.Tools.EndPerformanceCounter("Main render");
  87734. });
  87735. }
  87736. else {
  87737. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87738. this._onBeforeDrawPhaseObserver = null;
  87739. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87740. this._onAfterDrawPhaseObserver = null;
  87741. }
  87742. },
  87743. enumerable: true,
  87744. configurable: true
  87745. });
  87746. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87747. /**
  87748. * Gets the perf counter used for draw calls
  87749. */
  87750. get: function () {
  87751. return this.scene.getEngine()._drawCalls;
  87752. },
  87753. enumerable: true,
  87754. configurable: true
  87755. });
  87756. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87757. /**
  87758. * Gets the perf counter used for texture collisions
  87759. */
  87760. get: function () {
  87761. return this.scene.getEngine()._textureCollisions;
  87762. },
  87763. enumerable: true,
  87764. configurable: true
  87765. });
  87766. SceneInstrumentation.prototype.dispose = function () {
  87767. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87768. this._onAfterRenderObserver = null;
  87769. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87770. this._onBeforeActiveMeshesEvaluationObserver = null;
  87771. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87772. this._onAfterActiveMeshesEvaluationObserver = null;
  87773. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87774. this._onBeforeRenderTargetsRenderObserver = null;
  87775. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87776. this._onAfterRenderTargetsRenderObserver = null;
  87777. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87778. this._onBeforeAnimationsObserver = null;
  87779. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87780. this._onBeforeParticlesRenderingObserver = null;
  87781. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87782. this._onAfterParticlesRenderingObserver = null;
  87783. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87784. this._onBeforeSpritesRenderingObserver = null;
  87785. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87786. this._onAfterSpritesRenderingObserver = null;
  87787. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87788. this._onBeforeDrawPhaseObserver = null;
  87789. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87790. this._onAfterDrawPhaseObserver = null;
  87791. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87792. this._onBeforePhysicsObserver = null;
  87793. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87794. this._onAfterPhysicsObserver = null;
  87795. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87796. this._onAfterAnimationsObserver = null;
  87797. this.scene = null;
  87798. };
  87799. return SceneInstrumentation;
  87800. }());
  87801. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87802. })(BABYLON || (BABYLON = {}));
  87803. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87804. var BABYLON;
  87805. (function (BABYLON) {
  87806. var _TimeToken = /** @class */ (function () {
  87807. function _TimeToken() {
  87808. this._timeElapsedQueryEnded = false;
  87809. }
  87810. return _TimeToken;
  87811. }());
  87812. BABYLON._TimeToken = _TimeToken;
  87813. })(BABYLON || (BABYLON = {}));
  87814. //# sourceMappingURL=babylon.timeToken.js.map
  87815. var BABYLON;
  87816. (function (BABYLON) {
  87817. /**
  87818. * Background material defines definition.
  87819. * @ignore Mainly internal Use
  87820. */
  87821. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  87822. __extends(BackgroundMaterialDefines, _super);
  87823. /**
  87824. * Constructor of the defines.
  87825. */
  87826. function BackgroundMaterialDefines() {
  87827. var _this = _super.call(this) || this;
  87828. /**
  87829. * True if the diffuse texture is in use.
  87830. */
  87831. _this.DIFFUSE = false;
  87832. /**
  87833. * The direct UV channel to use.
  87834. */
  87835. _this.DIFFUSEDIRECTUV = 0;
  87836. /**
  87837. * True if the diffuse texture is in gamma space.
  87838. */
  87839. _this.GAMMADIFFUSE = false;
  87840. /**
  87841. * True if the diffuse texture has opacity in the alpha channel.
  87842. */
  87843. _this.DIFFUSEHASALPHA = false;
  87844. /**
  87845. * True if you want the material to fade to transparent at grazing angle.
  87846. */
  87847. _this.OPACITYFRESNEL = false;
  87848. /**
  87849. * True if an extra blur needs to be added in the reflection.
  87850. */
  87851. _this.REFLECTIONBLUR = false;
  87852. /**
  87853. * True if you want the material to fade to reflection at grazing angle.
  87854. */
  87855. _this.REFLECTIONFRESNEL = false;
  87856. /**
  87857. * True if you want the material to falloff as far as you move away from the scene center.
  87858. */
  87859. _this.REFLECTIONFALLOFF = false;
  87860. /**
  87861. * False if the current Webgl implementation does not support the texture lod extension.
  87862. */
  87863. _this.TEXTURELODSUPPORT = false;
  87864. /**
  87865. * True to ensure the data are premultiplied.
  87866. */
  87867. _this.PREMULTIPLYALPHA = false;
  87868. /**
  87869. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  87870. */
  87871. _this.USERGBCOLOR = false;
  87872. /**
  87873. * True to add noise in order to reduce the banding effect.
  87874. */
  87875. _this.NOISE = false;
  87876. /**
  87877. * is the reflection texture in BGR color scheme?
  87878. * Mainly used to solve a bug in ios10 video tag
  87879. */
  87880. _this.REFLECTIONBGR = false;
  87881. _this.IMAGEPROCESSING = false;
  87882. _this.VIGNETTE = false;
  87883. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87884. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87885. _this.TONEMAPPING = false;
  87886. _this.CONTRAST = false;
  87887. _this.COLORCURVES = false;
  87888. _this.COLORGRADING = false;
  87889. _this.COLORGRADING3D = false;
  87890. _this.SAMPLER3DGREENDEPTH = false;
  87891. _this.SAMPLER3DBGRMAP = false;
  87892. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87893. _this.EXPOSURE = false;
  87894. // Reflection.
  87895. _this.REFLECTION = false;
  87896. _this.REFLECTIONMAP_3D = false;
  87897. _this.REFLECTIONMAP_SPHERICAL = false;
  87898. _this.REFLECTIONMAP_PLANAR = false;
  87899. _this.REFLECTIONMAP_CUBIC = false;
  87900. _this.REFLECTIONMAP_PROJECTION = false;
  87901. _this.REFLECTIONMAP_SKYBOX = false;
  87902. _this.REFLECTIONMAP_EXPLICIT = false;
  87903. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87904. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87905. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87906. _this.INVERTCUBICMAP = false;
  87907. _this.REFLECTIONMAP_OPPOSITEZ = false;
  87908. _this.LODINREFLECTIONALPHA = false;
  87909. _this.GAMMAREFLECTION = false;
  87910. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  87911. // Default BJS.
  87912. _this.MAINUV1 = false;
  87913. _this.MAINUV2 = false;
  87914. _this.UV1 = false;
  87915. _this.UV2 = false;
  87916. _this.CLIPPLANE = false;
  87917. _this.POINTSIZE = false;
  87918. _this.FOG = false;
  87919. _this.NORMAL = false;
  87920. _this.NUM_BONE_INFLUENCERS = 0;
  87921. _this.BonesPerMesh = 0;
  87922. _this.INSTANCES = false;
  87923. _this.SHADOWFLOAT = false;
  87924. _this.rebuild();
  87925. return _this;
  87926. }
  87927. return BackgroundMaterialDefines;
  87928. }(BABYLON.MaterialDefines));
  87929. /**
  87930. * Background material used to create an efficient environement around your scene.
  87931. */
  87932. var BackgroundMaterial = /** @class */ (function (_super) {
  87933. __extends(BackgroundMaterial, _super);
  87934. /**
  87935. * Instantiates a Background Material in the given scene
  87936. * @param name The friendly name of the material
  87937. * @param scene The scene to add the material to
  87938. */
  87939. function BackgroundMaterial(name, scene) {
  87940. var _this = _super.call(this, name, scene) || this;
  87941. /**
  87942. * Key light Color (multiply against the R channel of the environement texture)
  87943. */
  87944. _this.primaryColor = BABYLON.Color3.White();
  87945. /**
  87946. * Key light Level (allowing HDR output of the background)
  87947. */
  87948. _this.primaryLevel = 1;
  87949. /**
  87950. * Secondary light Color (multiply against the G channel of the environement texture)
  87951. */
  87952. _this.secondaryColor = BABYLON.Color3.Gray();
  87953. /**
  87954. * Secondary light Level (allowing HDR output of the background)
  87955. */
  87956. _this.secondaryLevel = 1;
  87957. /**
  87958. * Tertiary light Color (multiply against the B channel of the environement texture)
  87959. */
  87960. _this.tertiaryColor = BABYLON.Color3.Black();
  87961. /**
  87962. * Tertiary light Level (allowing HDR output of the background)
  87963. */
  87964. _this.tertiaryLevel = 1;
  87965. /**
  87966. * Reflection Texture used in the material.
  87967. * Should be author in a specific way for the best result (refer to the documentation).
  87968. */
  87969. _this.reflectionTexture = null;
  87970. /**
  87971. * Reflection Texture level of blur.
  87972. *
  87973. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87974. * texture twice.
  87975. */
  87976. _this.reflectionBlur = 0;
  87977. /**
  87978. * Diffuse Texture used in the material.
  87979. * Should be author in a specific way for the best result (refer to the documentation).
  87980. */
  87981. _this.diffuseTexture = null;
  87982. _this._shadowLights = null;
  87983. /**
  87984. * Specify the list of lights casting shadow on the material.
  87985. * All scene shadow lights will be included if null.
  87986. */
  87987. _this.shadowLights = null;
  87988. /**
  87989. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87990. * soft lighting on the background.
  87991. */
  87992. _this.shadowBlurScale = 1;
  87993. /**
  87994. * Helps adjusting the shadow to a softer level if required.
  87995. * 0 means black shadows and 1 means no shadows.
  87996. */
  87997. _this.shadowLevel = 0;
  87998. /**
  87999. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88000. * It is usually zero but might be interesting to modify according to your setup.
  88001. */
  88002. _this.sceneCenter = BABYLON.Vector3.Zero();
  88003. /**
  88004. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88005. * This helps ensuring a nice transition when the camera goes under the ground.
  88006. */
  88007. _this.opacityFresnel = true;
  88008. /**
  88009. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88010. * This helps adding a mirror texture on the ground.
  88011. */
  88012. _this.reflectionFresnel = false;
  88013. /**
  88014. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88015. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88016. */
  88017. _this.reflectionFalloffDistance = 0.0;
  88018. /**
  88019. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88020. */
  88021. _this.reflectionAmount = 1.0;
  88022. /**
  88023. * This specifies the weight of the reflection at grazing angle.
  88024. */
  88025. _this.reflectionReflectance0 = 0.05;
  88026. /**
  88027. * This specifies the weight of the reflection at a perpendicular point of view.
  88028. */
  88029. _this.reflectionReflectance90 = 0.5;
  88030. /**
  88031. * Helps to directly use the maps channels instead of their level.
  88032. */
  88033. _this.useRGBColor = true;
  88034. /**
  88035. * This helps reducing the banding effect that could occur on the background.
  88036. */
  88037. _this.enableNoise = false;
  88038. _this._fovMultiplier = 1.0;
  88039. /**
  88040. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88041. * @type {boolean}
  88042. */
  88043. _this.useEquirectangularFOV = false;
  88044. _this._maxSimultaneousLights = 4;
  88045. /**
  88046. * Number of Simultaneous lights allowed on the material.
  88047. */
  88048. _this.maxSimultaneousLights = 4;
  88049. /**
  88050. * Keep track of the image processing observer to allow dispose and replace.
  88051. */
  88052. _this._imageProcessingObserver = null;
  88053. /**
  88054. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88055. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88056. */
  88057. _this.switchToBGR = false;
  88058. // Temp values kept as cache in the material.
  88059. _this._renderTargets = new BABYLON.SmartArray(16);
  88060. _this._reflectionControls = BABYLON.Vector4.Zero();
  88061. // Setup the default processing configuration to the scene.
  88062. _this._attachImageProcessingConfiguration(null);
  88063. _this.getRenderTargetTextures = function () {
  88064. _this._renderTargets.reset();
  88065. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88066. _this._renderTargets.push(_this._diffuseTexture);
  88067. }
  88068. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88069. _this._renderTargets.push(_this._reflectionTexture);
  88070. }
  88071. return _this._renderTargets;
  88072. };
  88073. return _this;
  88074. }
  88075. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88076. /**
  88077. * Sets the reflection reflectance fresnel values according to the default standard
  88078. * empirically know to work well :-)
  88079. */
  88080. set: function (value) {
  88081. var reflectionWeight = value;
  88082. if (reflectionWeight < 0.5) {
  88083. reflectionWeight = reflectionWeight * 2.0;
  88084. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88085. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88086. }
  88087. else {
  88088. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88089. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88090. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88091. }
  88092. },
  88093. enumerable: true,
  88094. configurable: true
  88095. });
  88096. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88097. /**
  88098. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88099. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88100. * Recommended to be keep at 1.0 except for special cases.
  88101. */
  88102. get: function () {
  88103. return this._fovMultiplier;
  88104. },
  88105. set: function (value) {
  88106. if (isNaN(value)) {
  88107. value = 1.0;
  88108. }
  88109. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88110. },
  88111. enumerable: true,
  88112. configurable: true
  88113. });
  88114. /**
  88115. * Attaches a new image processing configuration to the PBR Material.
  88116. * @param configuration (if null the scene configuration will be use)
  88117. */
  88118. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88119. var _this = this;
  88120. if (configuration === this._imageProcessingConfiguration) {
  88121. return;
  88122. }
  88123. // Detaches observer.
  88124. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88125. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88126. }
  88127. // Pick the scene configuration if needed.
  88128. if (!configuration) {
  88129. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88130. }
  88131. else {
  88132. this._imageProcessingConfiguration = configuration;
  88133. }
  88134. // Attaches observer.
  88135. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88136. _this._markAllSubMeshesAsImageProcessingDirty();
  88137. });
  88138. };
  88139. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88140. /**
  88141. * Gets the image processing configuration used either in this material.
  88142. */
  88143. get: function () {
  88144. return this._imageProcessingConfiguration;
  88145. },
  88146. /**
  88147. * Sets the Default image processing configuration used either in the this material.
  88148. *
  88149. * If sets to null, the scene one is in use.
  88150. */
  88151. set: function (value) {
  88152. this._attachImageProcessingConfiguration(value);
  88153. // Ensure the effect will be rebuilt.
  88154. this._markAllSubMeshesAsTexturesDirty();
  88155. },
  88156. enumerable: true,
  88157. configurable: true
  88158. });
  88159. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88160. /**
  88161. * Gets wether the color curves effect is enabled.
  88162. */
  88163. get: function () {
  88164. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88165. },
  88166. /**
  88167. * Sets wether the color curves effect is enabled.
  88168. */
  88169. set: function (value) {
  88170. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88171. },
  88172. enumerable: true,
  88173. configurable: true
  88174. });
  88175. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88176. /**
  88177. * Gets wether the color grading effect is enabled.
  88178. */
  88179. get: function () {
  88180. return this.imageProcessingConfiguration.colorGradingEnabled;
  88181. },
  88182. /**
  88183. * Gets wether the color grading effect is enabled.
  88184. */
  88185. set: function (value) {
  88186. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88187. },
  88188. enumerable: true,
  88189. configurable: true
  88190. });
  88191. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88192. /**
  88193. * Gets wether tonemapping is enabled or not.
  88194. */
  88195. get: function () {
  88196. return this._imageProcessingConfiguration.toneMappingEnabled;
  88197. },
  88198. /**
  88199. * Sets wether tonemapping is enabled or not
  88200. */
  88201. set: function (value) {
  88202. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88203. },
  88204. enumerable: true,
  88205. configurable: true
  88206. });
  88207. ;
  88208. ;
  88209. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88210. /**
  88211. * The camera exposure used on this material.
  88212. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88213. * This corresponds to a photographic exposure.
  88214. */
  88215. get: function () {
  88216. return this._imageProcessingConfiguration.exposure;
  88217. },
  88218. /**
  88219. * The camera exposure used on this material.
  88220. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88221. * This corresponds to a photographic exposure.
  88222. */
  88223. set: function (value) {
  88224. this._imageProcessingConfiguration.exposure = value;
  88225. },
  88226. enumerable: true,
  88227. configurable: true
  88228. });
  88229. ;
  88230. ;
  88231. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88232. /**
  88233. * Gets The camera contrast used on this material.
  88234. */
  88235. get: function () {
  88236. return this._imageProcessingConfiguration.contrast;
  88237. },
  88238. /**
  88239. * Sets The camera contrast used on this material.
  88240. */
  88241. set: function (value) {
  88242. this._imageProcessingConfiguration.contrast = value;
  88243. },
  88244. enumerable: true,
  88245. configurable: true
  88246. });
  88247. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88248. /**
  88249. * Gets the Color Grading 2D Lookup Texture.
  88250. */
  88251. get: function () {
  88252. return this._imageProcessingConfiguration.colorGradingTexture;
  88253. },
  88254. /**
  88255. * Sets the Color Grading 2D Lookup Texture.
  88256. */
  88257. set: function (value) {
  88258. this.imageProcessingConfiguration.colorGradingTexture = value;
  88259. },
  88260. enumerable: true,
  88261. configurable: true
  88262. });
  88263. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88264. /**
  88265. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88266. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88267. * 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;
  88268. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88269. */
  88270. get: function () {
  88271. return this.imageProcessingConfiguration.colorCurves;
  88272. },
  88273. /**
  88274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88276. * 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;
  88277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88278. */
  88279. set: function (value) {
  88280. this.imageProcessingConfiguration.colorCurves = value;
  88281. },
  88282. enumerable: true,
  88283. configurable: true
  88284. });
  88285. /**
  88286. * The entire material has been created in order to prevent overdraw.
  88287. * @returns false
  88288. */
  88289. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88290. return true;
  88291. };
  88292. /**
  88293. * The entire material has been created in order to prevent overdraw.
  88294. * @returns true if blending is enable
  88295. */
  88296. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88297. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88298. };
  88299. /**
  88300. * Checks wether the material is ready to be rendered for a given mesh.
  88301. * @param mesh The mesh to render
  88302. * @param subMesh The submesh to check against
  88303. * @param useInstances Specify wether or not the material is used with instances
  88304. * @returns true if all the dependencies are ready (Textures, Effects...)
  88305. */
  88306. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88307. var _this = this;
  88308. if (useInstances === void 0) { useInstances = false; }
  88309. if (subMesh.effect && this.isFrozen) {
  88310. if (this._wasPreviouslyReady) {
  88311. return true;
  88312. }
  88313. }
  88314. if (!subMesh._materialDefines) {
  88315. subMesh._materialDefines = new BackgroundMaterialDefines();
  88316. }
  88317. var scene = this.getScene();
  88318. var defines = subMesh._materialDefines;
  88319. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88320. if (defines._renderId === scene.getRenderId()) {
  88321. return true;
  88322. }
  88323. }
  88324. var engine = scene.getEngine();
  88325. // Lights
  88326. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88327. defines._needNormals = true;
  88328. // Textures
  88329. if (defines._areTexturesDirty) {
  88330. defines._needUVs = false;
  88331. if (scene.texturesEnabled) {
  88332. if (scene.getEngine().getCaps().textureLOD) {
  88333. defines.TEXTURELODSUPPORT = true;
  88334. }
  88335. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88336. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88337. return false;
  88338. }
  88339. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88340. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88341. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88342. defines.OPACITYFRESNEL = this._opacityFresnel;
  88343. }
  88344. else {
  88345. defines.DIFFUSE = false;
  88346. defines.DIFFUSEHASALPHA = false;
  88347. defines.GAMMADIFFUSE = false;
  88348. defines.OPACITYFRESNEL = false;
  88349. }
  88350. var reflectionTexture = this._reflectionTexture;
  88351. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88352. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88353. return false;
  88354. }
  88355. defines.REFLECTION = true;
  88356. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88357. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88358. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88359. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88360. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88361. defines.REFLECTIONBGR = this.switchToBGR;
  88362. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88363. defines.INVERTCUBICMAP = true;
  88364. }
  88365. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88366. switch (reflectionTexture.coordinatesMode) {
  88367. case BABYLON.Texture.CUBIC_MODE:
  88368. case BABYLON.Texture.INVCUBIC_MODE:
  88369. defines.REFLECTIONMAP_CUBIC = true;
  88370. break;
  88371. case BABYLON.Texture.EXPLICIT_MODE:
  88372. defines.REFLECTIONMAP_EXPLICIT = true;
  88373. break;
  88374. case BABYLON.Texture.PLANAR_MODE:
  88375. defines.REFLECTIONMAP_PLANAR = true;
  88376. break;
  88377. case BABYLON.Texture.PROJECTION_MODE:
  88378. defines.REFLECTIONMAP_PROJECTION = true;
  88379. break;
  88380. case BABYLON.Texture.SKYBOX_MODE:
  88381. defines.REFLECTIONMAP_SKYBOX = true;
  88382. break;
  88383. case BABYLON.Texture.SPHERICAL_MODE:
  88384. defines.REFLECTIONMAP_SPHERICAL = true;
  88385. break;
  88386. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88387. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88388. break;
  88389. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88390. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88391. break;
  88392. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88393. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88394. break;
  88395. }
  88396. if (this.reflectionFresnel) {
  88397. defines.REFLECTIONFRESNEL = true;
  88398. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88399. this._reflectionControls.x = this.reflectionAmount;
  88400. this._reflectionControls.y = this.reflectionReflectance0;
  88401. this._reflectionControls.z = this.reflectionReflectance90;
  88402. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88403. }
  88404. else {
  88405. defines.REFLECTIONFRESNEL = false;
  88406. defines.REFLECTIONFALLOFF = false;
  88407. }
  88408. }
  88409. else {
  88410. defines.REFLECTION = false;
  88411. defines.REFLECTIONFALLOFF = false;
  88412. defines.REFLECTIONBLUR = false;
  88413. defines.REFLECTIONMAP_3D = false;
  88414. defines.REFLECTIONMAP_SPHERICAL = false;
  88415. defines.REFLECTIONMAP_PLANAR = false;
  88416. defines.REFLECTIONMAP_CUBIC = false;
  88417. defines.REFLECTIONMAP_PROJECTION = false;
  88418. defines.REFLECTIONMAP_SKYBOX = false;
  88419. defines.REFLECTIONMAP_EXPLICIT = false;
  88420. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88421. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88422. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88423. defines.INVERTCUBICMAP = false;
  88424. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88425. defines.LODINREFLECTIONALPHA = false;
  88426. defines.GAMMAREFLECTION = false;
  88427. }
  88428. }
  88429. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88430. defines.USERGBCOLOR = this._useRGBColor;
  88431. defines.NOISE = this._enableNoise;
  88432. }
  88433. if (defines._areImageProcessingDirty) {
  88434. if (!this._imageProcessingConfiguration.isReady()) {
  88435. return false;
  88436. }
  88437. this._imageProcessingConfiguration.prepareDefines(defines);
  88438. }
  88439. // Misc.
  88440. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88441. // Values that need to be evaluated on every frame
  88442. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88443. // Attribs
  88444. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88445. if (mesh) {
  88446. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88447. mesh.createNormals(true);
  88448. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88449. }
  88450. }
  88451. }
  88452. // Get correct effect
  88453. if (defines.isDirty) {
  88454. defines.markAsProcessed();
  88455. scene.resetCachedMaterial();
  88456. // Fallbacks
  88457. var fallbacks = new BABYLON.EffectFallbacks();
  88458. if (defines.FOG) {
  88459. fallbacks.addFallback(0, "FOG");
  88460. }
  88461. if (defines.POINTSIZE) {
  88462. fallbacks.addFallback(1, "POINTSIZE");
  88463. }
  88464. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88465. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88466. fallbacks.addCPUSkinningFallback(0, mesh);
  88467. }
  88468. //Attributes
  88469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88470. if (defines.NORMAL) {
  88471. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88472. }
  88473. if (defines.UV1) {
  88474. attribs.push(BABYLON.VertexBuffer.UVKind);
  88475. }
  88476. if (defines.UV2) {
  88477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88478. }
  88479. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88480. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88481. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88482. "vFogInfos", "vFogColor", "pointSize",
  88483. "vClipPlane", "mBones",
  88484. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88485. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88486. "shadowLevel", "alpha",
  88487. "vBackgroundCenter", "vReflectionControl",
  88488. "vDiffuseInfos", "diffuseMatrix",
  88489. ];
  88490. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88491. var uniformBuffers = ["Material", "Scene"];
  88492. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88493. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88494. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88495. uniformsNames: uniforms,
  88496. uniformBuffersNames: uniformBuffers,
  88497. samplers: samplers,
  88498. defines: defines,
  88499. maxSimultaneousLights: this._maxSimultaneousLights
  88500. });
  88501. var onCompiled = function (effect) {
  88502. if (_this.onCompiled) {
  88503. _this.onCompiled(effect);
  88504. }
  88505. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88506. };
  88507. var join = defines.toString();
  88508. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88509. attributes: attribs,
  88510. uniformsNames: uniforms,
  88511. uniformBuffersNames: uniformBuffers,
  88512. samplers: samplers,
  88513. defines: join,
  88514. fallbacks: fallbacks,
  88515. onCompiled: onCompiled,
  88516. onError: this.onError,
  88517. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88518. }, engine), defines);
  88519. this.buildUniformLayout();
  88520. }
  88521. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88522. return false;
  88523. }
  88524. defines._renderId = scene.getRenderId();
  88525. this._wasPreviouslyReady = true;
  88526. return true;
  88527. };
  88528. /**
  88529. * Build the uniform buffer used in the material.
  88530. */
  88531. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88532. // Order is important !
  88533. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88534. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88535. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88536. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88537. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88538. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88539. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88540. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88541. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88542. this._uniformBuffer.addUniform("pointSize", 1);
  88543. this._uniformBuffer.addUniform("shadowLevel", 1);
  88544. this._uniformBuffer.addUniform("alpha", 1);
  88545. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88546. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88547. this._uniformBuffer.create();
  88548. };
  88549. /**
  88550. * Unbind the material.
  88551. */
  88552. BackgroundMaterial.prototype.unbind = function () {
  88553. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88554. this._uniformBuffer.setTexture("diffuseSampler", null);
  88555. }
  88556. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88557. this._uniformBuffer.setTexture("reflectionSampler", null);
  88558. }
  88559. _super.prototype.unbind.call(this);
  88560. };
  88561. /**
  88562. * Bind only the world matrix to the material.
  88563. * @param world The world matrix to bind.
  88564. */
  88565. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88566. this._activeEffect.setMatrix("world", world);
  88567. };
  88568. /**
  88569. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88570. * @param world The world matrix to bind.
  88571. * @param subMesh The submesh to bind for.
  88572. */
  88573. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88574. var scene = this.getScene();
  88575. var defines = subMesh._materialDefines;
  88576. if (!defines) {
  88577. return;
  88578. }
  88579. var effect = subMesh.effect;
  88580. if (!effect) {
  88581. return;
  88582. }
  88583. this._activeEffect = effect;
  88584. // Matrices
  88585. this.bindOnlyWorldMatrix(world);
  88586. // Bones
  88587. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88588. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88589. if (mustRebind) {
  88590. this._uniformBuffer.bindToEffect(effect, "Material");
  88591. this.bindViewProjection(effect);
  88592. var reflectionTexture = this._reflectionTexture;
  88593. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88594. // Texture uniforms
  88595. if (scene.texturesEnabled) {
  88596. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88597. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88598. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88599. }
  88600. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88601. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88602. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88603. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88604. }
  88605. }
  88606. if (this.shadowLevel > 0) {
  88607. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88608. }
  88609. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88610. // Point size
  88611. if (this.pointsCloud) {
  88612. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88613. }
  88614. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88615. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88616. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88617. }
  88618. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88619. // Textures
  88620. if (scene.texturesEnabled) {
  88621. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88622. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88623. }
  88624. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88625. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88626. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88627. }
  88628. else if (!defines.REFLECTIONBLUR) {
  88629. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88630. }
  88631. else {
  88632. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88633. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88634. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88635. }
  88636. if (defines.REFLECTIONFRESNEL) {
  88637. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88638. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88639. }
  88640. }
  88641. }
  88642. // Clip plane
  88643. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88644. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88645. }
  88646. if (mustRebind || !this.isFrozen) {
  88647. if (scene.lightsEnabled) {
  88648. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88649. }
  88650. // View
  88651. this.bindView(effect);
  88652. // Fog
  88653. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88654. // image processing
  88655. this._imageProcessingConfiguration.bind(this._activeEffect);
  88656. }
  88657. this._uniformBuffer.update();
  88658. this._afterBind(mesh);
  88659. };
  88660. /**
  88661. * Dispose the material.
  88662. * @param forceDisposeEffect Force disposal of the associated effect.
  88663. * @param forceDisposeTextures Force disposal of the associated textures.
  88664. */
  88665. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88666. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88667. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88668. if (forceDisposeTextures) {
  88669. if (this.diffuseTexture) {
  88670. this.diffuseTexture.dispose();
  88671. }
  88672. if (this.reflectionTexture) {
  88673. this.reflectionTexture.dispose();
  88674. }
  88675. }
  88676. this._renderTargets.dispose();
  88677. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88678. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88679. }
  88680. _super.prototype.dispose.call(this, forceDisposeEffect);
  88681. };
  88682. /**
  88683. * Clones the material.
  88684. * @param name The cloned name.
  88685. * @returns The cloned material.
  88686. */
  88687. BackgroundMaterial.prototype.clone = function (name) {
  88688. var _this = this;
  88689. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88690. };
  88691. /**
  88692. * Serializes the current material to its JSON representation.
  88693. * @returns The JSON representation.
  88694. */
  88695. BackgroundMaterial.prototype.serialize = function () {
  88696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88697. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88698. return serializationObject;
  88699. };
  88700. /**
  88701. * Gets the class name of the material
  88702. * @returns "BackgroundMaterial"
  88703. */
  88704. BackgroundMaterial.prototype.getClassName = function () {
  88705. return "BackgroundMaterial";
  88706. };
  88707. /**
  88708. * Parse a JSON input to create back a background material.
  88709. * @param source The JSON data to parse
  88710. * @param scene The scene to create the parsed material in
  88711. * @param rootUrl The root url of the assets the material depends upon
  88712. * @returns the instantiated BackgroundMaterial.
  88713. */
  88714. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88715. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88716. };
  88717. /**
  88718. * Standard reflectance value at parallel view angle.
  88719. */
  88720. BackgroundMaterial.StandardReflectance0 = 0.05;
  88721. /**
  88722. * Standard reflectance value at grazing angle.
  88723. */
  88724. BackgroundMaterial.StandardReflectance90 = 0.5;
  88725. __decorate([
  88726. BABYLON.serializeAsColor3()
  88727. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88728. __decorate([
  88729. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88730. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88731. __decorate([
  88732. BABYLON.serialize()
  88733. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88734. __decorate([
  88735. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88736. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88737. __decorate([
  88738. BABYLON.serializeAsColor3()
  88739. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88740. __decorate([
  88741. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88742. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88743. __decorate([
  88744. BABYLON.serialize()
  88745. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88746. __decorate([
  88747. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88748. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88749. __decorate([
  88750. BABYLON.serializeAsColor3()
  88751. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88752. __decorate([
  88753. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88754. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88755. __decorate([
  88756. BABYLON.serialize()
  88757. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88758. __decorate([
  88759. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88760. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88761. __decorate([
  88762. BABYLON.serializeAsTexture()
  88763. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88764. __decorate([
  88765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88766. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88767. __decorate([
  88768. BABYLON.serialize()
  88769. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88770. __decorate([
  88771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88772. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88773. __decorate([
  88774. BABYLON.serializeAsTexture()
  88775. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88776. __decorate([
  88777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88778. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88779. __decorate([
  88780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88781. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88782. __decorate([
  88783. BABYLON.serialize()
  88784. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88785. __decorate([
  88786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88787. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88788. __decorate([
  88789. BABYLON.serialize()
  88790. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88791. __decorate([
  88792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88793. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88794. __decorate([
  88795. BABYLON.serializeAsVector3()
  88796. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88797. __decorate([
  88798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88799. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88800. __decorate([
  88801. BABYLON.serialize()
  88802. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88803. __decorate([
  88804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88805. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  88806. __decorate([
  88807. BABYLON.serialize()
  88808. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  88809. __decorate([
  88810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88811. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  88812. __decorate([
  88813. BABYLON.serialize()
  88814. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  88815. __decorate([
  88816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88817. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  88818. __decorate([
  88819. BABYLON.serialize()
  88820. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  88821. __decorate([
  88822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88823. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  88824. __decorate([
  88825. BABYLON.serialize()
  88826. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  88827. __decorate([
  88828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88829. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  88830. __decorate([
  88831. BABYLON.serialize()
  88832. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  88833. __decorate([
  88834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88835. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  88836. __decorate([
  88837. BABYLON.serialize()
  88838. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  88839. __decorate([
  88840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88841. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  88842. __decorate([
  88843. BABYLON.serialize()
  88844. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  88845. __decorate([
  88846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88847. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  88848. __decorate([
  88849. BABYLON.serialize()
  88850. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  88851. __decorate([
  88852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88853. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  88854. __decorate([
  88855. BABYLON.serializeAsImageProcessingConfiguration()
  88856. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  88857. return BackgroundMaterial;
  88858. }(BABYLON.PushMaterial));
  88859. BABYLON.BackgroundMaterial = BackgroundMaterial;
  88860. })(BABYLON || (BABYLON = {}));
  88861. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  88862. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88863. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88864. s = arguments[i];
  88865. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88866. t[p] = s[p];
  88867. }
  88868. return t;
  88869. };
  88870. var BABYLON;
  88871. (function (BABYLON) {
  88872. /**
  88873. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  88874. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  88875. * It also helps with the default setup of your imageProcessing configuration.
  88876. */
  88877. var EnvironmentHelper = /** @class */ (function () {
  88878. /**
  88879. * constructor
  88880. * @param options
  88881. * @param scene The scene to add the material to
  88882. */
  88883. function EnvironmentHelper(options, scene) {
  88884. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  88885. this._scene = scene;
  88886. this._setupBackground();
  88887. this._setupImageProcessing();
  88888. }
  88889. /**
  88890. * Creates the default options for the helper.
  88891. */
  88892. EnvironmentHelper._getDefaultOptions = function () {
  88893. return {
  88894. createGround: true,
  88895. groundSize: 15,
  88896. groundTexture: this._groundTextureCDNUrl,
  88897. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88898. groundOpacity: 0.9,
  88899. enableGroundShadow: true,
  88900. groundShadowLevel: 0.5,
  88901. enableGroundMirror: false,
  88902. groundMirrorSizeRatio: 0.3,
  88903. groundMirrorBlurKernel: 64,
  88904. groundMirrorAmount: 1,
  88905. groundMirrorFresnelWeight: 1,
  88906. groundMirrorFallOffDistance: 0,
  88907. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  88908. groundYBias: 0.00001,
  88909. createSkybox: true,
  88910. skyboxSize: 20,
  88911. skyboxTexture: this._skyboxTextureCDNUrl,
  88912. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88913. backgroundYRotation: 0,
  88914. sizeAuto: true,
  88915. rootPosition: BABYLON.Vector3.Zero(),
  88916. setupImageProcessing: true,
  88917. environmentTexture: this._environmentTextureCDNUrl,
  88918. cameraExposure: 0.8,
  88919. cameraContrast: 1.2,
  88920. toneMappingEnabled: true,
  88921. };
  88922. };
  88923. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88924. /**
  88925. * Gets the root mesh created by the helper.
  88926. */
  88927. get: function () {
  88928. return this._rootMesh;
  88929. },
  88930. enumerable: true,
  88931. configurable: true
  88932. });
  88933. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88934. /**
  88935. * Gets the skybox created by the helper.
  88936. */
  88937. get: function () {
  88938. return this._skybox;
  88939. },
  88940. enumerable: true,
  88941. configurable: true
  88942. });
  88943. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88944. /**
  88945. * Gets the skybox texture created by the helper.
  88946. */
  88947. get: function () {
  88948. return this._skyboxTexture;
  88949. },
  88950. enumerable: true,
  88951. configurable: true
  88952. });
  88953. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88954. /**
  88955. * Gets the skybox material created by the helper.
  88956. */
  88957. get: function () {
  88958. return this._skyboxMaterial;
  88959. },
  88960. enumerable: true,
  88961. configurable: true
  88962. });
  88963. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88964. /**
  88965. * Gets the ground mesh created by the helper.
  88966. */
  88967. get: function () {
  88968. return this._ground;
  88969. },
  88970. enumerable: true,
  88971. configurable: true
  88972. });
  88973. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88974. /**
  88975. * Gets the ground texture created by the helper.
  88976. */
  88977. get: function () {
  88978. return this._groundTexture;
  88979. },
  88980. enumerable: true,
  88981. configurable: true
  88982. });
  88983. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88984. /**
  88985. * Gets the ground mirror created by the helper.
  88986. */
  88987. get: function () {
  88988. return this._groundMirror;
  88989. },
  88990. enumerable: true,
  88991. configurable: true
  88992. });
  88993. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88994. /**
  88995. * Gets the ground mirror render list to helps pushing the meshes
  88996. * you wish in the ground reflection.
  88997. */
  88998. get: function () {
  88999. if (this._groundMirror) {
  89000. return this._groundMirror.renderList;
  89001. }
  89002. return null;
  89003. },
  89004. enumerable: true,
  89005. configurable: true
  89006. });
  89007. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89008. /**
  89009. * Gets the ground material created by the helper.
  89010. */
  89011. get: function () {
  89012. return this._groundMaterial;
  89013. },
  89014. enumerable: true,
  89015. configurable: true
  89016. });
  89017. /**
  89018. * Updates the background according to the new options
  89019. * @param options
  89020. */
  89021. EnvironmentHelper.prototype.updateOptions = function (options) {
  89022. var newOptions = __assign({}, this._options, options);
  89023. if (this._ground && !newOptions.createGround) {
  89024. this._ground.dispose();
  89025. this._ground = null;
  89026. }
  89027. if (this._groundMaterial && !newOptions.createGround) {
  89028. this._groundMaterial.dispose();
  89029. this._groundMaterial = null;
  89030. }
  89031. if (this._groundTexture) {
  89032. if (this._options.groundTexture != newOptions.groundTexture) {
  89033. this._groundTexture.dispose();
  89034. this._groundTexture = null;
  89035. }
  89036. }
  89037. if (this._skybox && !newOptions.createSkybox) {
  89038. this._skybox.dispose();
  89039. this._skybox = null;
  89040. }
  89041. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89042. this._skyboxMaterial.dispose();
  89043. this._skyboxMaterial = null;
  89044. }
  89045. if (this._skyboxTexture) {
  89046. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89047. this._skyboxTexture.dispose();
  89048. this._skyboxTexture = null;
  89049. }
  89050. }
  89051. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89052. this._groundMirror.dispose();
  89053. this._groundMirror = null;
  89054. }
  89055. if (this._scene.environmentTexture) {
  89056. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89057. this._scene.environmentTexture.dispose();
  89058. }
  89059. }
  89060. this._options = newOptions;
  89061. this._setupBackground();
  89062. this._setupImageProcessing();
  89063. };
  89064. /**
  89065. * Sets the primary color of all the available elements.
  89066. * @param color
  89067. */
  89068. EnvironmentHelper.prototype.setMainColor = function (color) {
  89069. if (this.groundMaterial) {
  89070. this.groundMaterial.primaryColor = color;
  89071. }
  89072. if (this.skyboxMaterial) {
  89073. this.skyboxMaterial.primaryColor = color;
  89074. }
  89075. if (this.groundMirror) {
  89076. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89077. }
  89078. };
  89079. /**
  89080. * Setup the image processing according to the specified options.
  89081. */
  89082. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89083. if (this._options.setupImageProcessing) {
  89084. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89085. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89086. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89087. this._setupEnvironmentTexture();
  89088. }
  89089. };
  89090. /**
  89091. * Setup the environment texture according to the specified options.
  89092. */
  89093. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89094. if (this._scene.environmentTexture) {
  89095. return;
  89096. }
  89097. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89098. this._scene.environmentTexture = this._options.environmentTexture;
  89099. return;
  89100. }
  89101. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89102. this._scene.environmentTexture = environmentTexture;
  89103. };
  89104. /**
  89105. * Setup the background according to the specified options.
  89106. */
  89107. EnvironmentHelper.prototype._setupBackground = function () {
  89108. if (!this._rootMesh) {
  89109. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89110. }
  89111. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89112. var sceneSize = this._getSceneSize();
  89113. if (this._options.createGround) {
  89114. this._setupGround(sceneSize);
  89115. this._setupGroundMaterial();
  89116. this._setupGroundDiffuseTexture();
  89117. if (this._options.enableGroundMirror) {
  89118. this._setupGroundMirrorTexture(sceneSize);
  89119. }
  89120. this._setupMirrorInGroundMaterial();
  89121. }
  89122. if (this._options.createSkybox) {
  89123. this._setupSkybox(sceneSize);
  89124. this._setupSkyboxMaterial();
  89125. this._setupSkyboxReflectionTexture();
  89126. }
  89127. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89128. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89129. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89130. };
  89131. /**
  89132. * Get the scene sizes according to the setup.
  89133. */
  89134. EnvironmentHelper.prototype._getSceneSize = function () {
  89135. var _this = this;
  89136. var groundSize = this._options.groundSize;
  89137. var skyboxSize = this._options.skyboxSize;
  89138. var rootPosition = this._options.rootPosition;
  89139. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89140. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89141. }
  89142. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89143. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89144. });
  89145. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89146. if (this._options.sizeAuto) {
  89147. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89148. this._scene.activeCamera.upperRadiusLimit) {
  89149. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89150. skyboxSize = groundSize;
  89151. }
  89152. var sceneDiagonalLenght = sceneDiagonal.length();
  89153. if (sceneDiagonalLenght > groundSize) {
  89154. groundSize = sceneDiagonalLenght * 2;
  89155. skyboxSize = groundSize;
  89156. }
  89157. // 10 % bigger.
  89158. groundSize *= 1.1;
  89159. skyboxSize *= 1.5;
  89160. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89161. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89162. }
  89163. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89164. };
  89165. /**
  89166. * Setup the ground according to the specified options.
  89167. */
  89168. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89169. var _this = this;
  89170. if (!this._ground) {
  89171. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89172. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89173. this._ground.parent = this._rootMesh;
  89174. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89175. }
  89176. this._ground.receiveShadows = this._options.enableGroundShadow;
  89177. };
  89178. /**
  89179. * Setup the ground material according to the specified options.
  89180. */
  89181. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89182. if (!this._groundMaterial) {
  89183. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89184. }
  89185. this._groundMaterial.alpha = this._options.groundOpacity;
  89186. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89187. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89188. this._groundMaterial.primaryLevel = 1;
  89189. this._groundMaterial.primaryColor = this._options.groundColor;
  89190. this._groundMaterial.secondaryLevel = 0;
  89191. this._groundMaterial.tertiaryLevel = 0;
  89192. this._groundMaterial.useRGBColor = false;
  89193. this._groundMaterial.enableNoise = true;
  89194. if (this._ground) {
  89195. this._ground.material = this._groundMaterial;
  89196. }
  89197. };
  89198. /**
  89199. * Setup the ground diffuse texture according to the specified options.
  89200. */
  89201. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89202. if (!this._groundMaterial) {
  89203. return;
  89204. }
  89205. if (this._groundTexture) {
  89206. return;
  89207. }
  89208. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89209. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89210. return;
  89211. }
  89212. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89213. diffuseTexture.gammaSpace = false;
  89214. diffuseTexture.hasAlpha = true;
  89215. this._groundMaterial.diffuseTexture = diffuseTexture;
  89216. };
  89217. /**
  89218. * Setup the ground mirror texture according to the specified options.
  89219. */
  89220. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89221. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89222. if (!this._groundMirror) {
  89223. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89224. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89225. this._groundMirror.anisotropicFilteringLevel = 1;
  89226. this._groundMirror.wrapU = wrapping;
  89227. this._groundMirror.wrapV = wrapping;
  89228. this._groundMirror.gammaSpace = false;
  89229. if (this._groundMirror.renderList) {
  89230. for (var i = 0; i < this._scene.meshes.length; i++) {
  89231. var mesh = this._scene.meshes[i];
  89232. if (mesh !== this._ground &&
  89233. mesh !== this._skybox &&
  89234. mesh !== this._rootMesh) {
  89235. this._groundMirror.renderList.push(mesh);
  89236. }
  89237. }
  89238. }
  89239. }
  89240. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89241. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89242. };
  89243. /**
  89244. * Setup the ground to receive the mirror texture.
  89245. */
  89246. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89247. if (this._groundMaterial) {
  89248. this._groundMaterial.reflectionTexture = this._groundMirror;
  89249. this._groundMaterial.reflectionFresnel = true;
  89250. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89251. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89252. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89253. }
  89254. };
  89255. /**
  89256. * Setup the skybox according to the specified options.
  89257. */
  89258. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89259. var _this = this;
  89260. if (!this._skybox) {
  89261. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89262. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89263. }
  89264. this._skybox.parent = this._rootMesh;
  89265. };
  89266. /**
  89267. * Setup the skybox material according to the specified options.
  89268. */
  89269. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89270. if (!this._skybox) {
  89271. return;
  89272. }
  89273. if (!this._skyboxMaterial) {
  89274. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89275. }
  89276. this._skyboxMaterial.useRGBColor = false;
  89277. this._skyboxMaterial.primaryLevel = 1;
  89278. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89279. this._skyboxMaterial.secondaryLevel = 0;
  89280. this._skyboxMaterial.tertiaryLevel = 0;
  89281. this._skyboxMaterial.enableNoise = true;
  89282. this._skybox.material = this._skyboxMaterial;
  89283. };
  89284. /**
  89285. * Setup the skybox reflection texture according to the specified options.
  89286. */
  89287. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89288. if (!this._skyboxMaterial) {
  89289. return;
  89290. }
  89291. if (this._skyboxTexture) {
  89292. return;
  89293. }
  89294. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89295. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89296. return;
  89297. }
  89298. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89299. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89300. this._skyboxTexture.gammaSpace = false;
  89301. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89302. };
  89303. /**
  89304. * Dispose all the elements created by the Helper.
  89305. */
  89306. EnvironmentHelper.prototype.dispose = function () {
  89307. if (this._groundMaterial) {
  89308. this._groundMaterial.dispose(true, true);
  89309. }
  89310. if (this._skyboxMaterial) {
  89311. this._skyboxMaterial.dispose(true, true);
  89312. }
  89313. this._rootMesh.dispose(false);
  89314. };
  89315. /**
  89316. * Default ground texture URL.
  89317. */
  89318. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89319. /**
  89320. * Default skybox texture URL.
  89321. */
  89322. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89323. /**
  89324. * Default environment texture URL.
  89325. */
  89326. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89327. return EnvironmentHelper;
  89328. }());
  89329. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89330. })(BABYLON || (BABYLON = {}));
  89331. //# sourceMappingURL=babylon.environmentHelper.js.map
  89332. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  89333. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  89334. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89335. var BABYLON;
  89336. (function (BABYLON) {
  89337. var GridMaterialDefines = /** @class */ (function (_super) {
  89338. __extends(GridMaterialDefines, _super);
  89339. function GridMaterialDefines() {
  89340. var _this = _super.call(this) || this;
  89341. _this.TRANSPARENT = false;
  89342. _this.FOG = false;
  89343. _this.PREMULTIPLYALPHA = false;
  89344. _this.rebuild();
  89345. return _this;
  89346. }
  89347. return GridMaterialDefines;
  89348. }(BABYLON.MaterialDefines));
  89349. /**
  89350. * The grid materials allows you to wrap any shape with a grid.
  89351. * Colors are customizable.
  89352. */
  89353. var GridMaterial = /** @class */ (function (_super) {
  89354. __extends(GridMaterial, _super);
  89355. /**
  89356. * constructor
  89357. * @param name The name given to the material in order to identify it afterwards.
  89358. * @param scene The scene the material is used in.
  89359. */
  89360. function GridMaterial(name, scene) {
  89361. var _this = _super.call(this, name, scene) || this;
  89362. /**
  89363. * Main color of the grid (e.g. between lines)
  89364. */
  89365. _this.mainColor = BABYLON.Color3.Black();
  89366. /**
  89367. * Color of the grid lines.
  89368. */
  89369. _this.lineColor = BABYLON.Color3.Teal();
  89370. /**
  89371. * The scale of the grid compared to unit.
  89372. */
  89373. _this.gridRatio = 1.0;
  89374. /**
  89375. * Allows setting an offset for the grid lines.
  89376. */
  89377. _this.gridOffset = BABYLON.Vector3.Zero();
  89378. /**
  89379. * The frequency of thicker lines.
  89380. */
  89381. _this.majorUnitFrequency = 10;
  89382. /**
  89383. * The visibility of minor units in the grid.
  89384. */
  89385. _this.minorUnitVisibility = 0.33;
  89386. /**
  89387. * The grid opacity outside of the lines.
  89388. */
  89389. _this.opacity = 1.0;
  89390. /**
  89391. * Determine RBG output is premultiplied by alpha value.
  89392. */
  89393. _this.preMultiplyAlpha = false;
  89394. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89395. return _this;
  89396. }
  89397. /**
  89398. * Returns wehter or not the grid requires alpha blending.
  89399. */
  89400. GridMaterial.prototype.needAlphaBlending = function () {
  89401. return this.opacity < 1.0;
  89402. };
  89403. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89404. return this.needAlphaBlending();
  89405. };
  89406. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89407. if (this.isFrozen) {
  89408. if (this._wasPreviouslyReady && subMesh.effect) {
  89409. return true;
  89410. }
  89411. }
  89412. if (!subMesh._materialDefines) {
  89413. subMesh._materialDefines = new GridMaterialDefines();
  89414. }
  89415. var defines = subMesh._materialDefines;
  89416. var scene = this.getScene();
  89417. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89418. if (this._renderId === scene.getRenderId()) {
  89419. return true;
  89420. }
  89421. }
  89422. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89423. defines.TRANSPARENT = !defines.TRANSPARENT;
  89424. defines.markAsUnprocessed();
  89425. }
  89426. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89427. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89428. defines.markAsUnprocessed();
  89429. }
  89430. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89431. // Get correct effect
  89432. if (defines.isDirty) {
  89433. defines.markAsProcessed();
  89434. scene.resetCachedMaterial();
  89435. // Attributes
  89436. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89437. // Defines
  89438. var join = defines.toString();
  89439. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89440. }
  89441. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89442. return false;
  89443. }
  89444. this._renderId = scene.getRenderId();
  89445. this._wasPreviouslyReady = true;
  89446. return true;
  89447. };
  89448. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89449. var scene = this.getScene();
  89450. var defines = subMesh._materialDefines;
  89451. if (!defines) {
  89452. return;
  89453. }
  89454. var effect = subMesh.effect;
  89455. if (!effect) {
  89456. return;
  89457. }
  89458. this._activeEffect = effect;
  89459. // Matrices
  89460. this.bindOnlyWorldMatrix(world);
  89461. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89462. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89463. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89464. // Uniforms
  89465. if (this._mustRebind(scene, effect)) {
  89466. this._activeEffect.setColor3("mainColor", this.mainColor);
  89467. this._activeEffect.setColor3("lineColor", this.lineColor);
  89468. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89469. this._gridControl.x = this.gridRatio;
  89470. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89471. this._gridControl.z = this.minorUnitVisibility;
  89472. this._gridControl.w = this.opacity;
  89473. this._activeEffect.setVector4("gridControl", this._gridControl);
  89474. }
  89475. // Fog
  89476. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89477. this._afterBind(mesh, this._activeEffect);
  89478. };
  89479. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89480. _super.prototype.dispose.call(this, forceDisposeEffect);
  89481. };
  89482. GridMaterial.prototype.clone = function (name) {
  89483. var _this = this;
  89484. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89485. };
  89486. GridMaterial.prototype.serialize = function () {
  89487. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89488. serializationObject.customType = "BABYLON.GridMaterial";
  89489. return serializationObject;
  89490. };
  89491. GridMaterial.prototype.getClassName = function () {
  89492. return "GridMaterial";
  89493. };
  89494. GridMaterial.Parse = function (source, scene, rootUrl) {
  89495. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89496. };
  89497. __decorate([
  89498. BABYLON.serializeAsColor3()
  89499. ], GridMaterial.prototype, "mainColor", void 0);
  89500. __decorate([
  89501. BABYLON.serializeAsColor3()
  89502. ], GridMaterial.prototype, "lineColor", void 0);
  89503. __decorate([
  89504. BABYLON.serialize()
  89505. ], GridMaterial.prototype, "gridRatio", void 0);
  89506. __decorate([
  89507. BABYLON.serializeAsColor3()
  89508. ], GridMaterial.prototype, "gridOffset", void 0);
  89509. __decorate([
  89510. BABYLON.serialize()
  89511. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89512. __decorate([
  89513. BABYLON.serialize()
  89514. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89515. __decorate([
  89516. BABYLON.serialize()
  89517. ], GridMaterial.prototype, "opacity", void 0);
  89518. __decorate([
  89519. BABYLON.serialize()
  89520. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89521. return GridMaterial;
  89522. }(BABYLON.PushMaterial));
  89523. BABYLON.GridMaterial = GridMaterial;
  89524. })(BABYLON || (BABYLON = {}));
  89525. //# sourceMappingURL=babylon.gridmaterial.js.map
  89526. 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}";
  89527. 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}";
  89528. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89529. var BABYLON;
  89530. (function (BABYLON) {
  89531. var GLTFLoaderCoordinateSystemMode;
  89532. (function (GLTFLoaderCoordinateSystemMode) {
  89533. /**
  89534. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89535. */
  89536. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89537. /**
  89538. * Sets the useRightHandedSystem flag on the scene.
  89539. */
  89540. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89541. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89542. var GLTFLoaderAnimationStartMode;
  89543. (function (GLTFLoaderAnimationStartMode) {
  89544. /**
  89545. * No animation will start.
  89546. */
  89547. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89548. /**
  89549. * The first animation will start.
  89550. */
  89551. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89552. /**
  89553. * All animations will start.
  89554. */
  89555. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89556. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89557. var GLTFLoaderState;
  89558. (function (GLTFLoaderState) {
  89559. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89560. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89561. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89562. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89563. var GLTFFileLoader = /** @class */ (function () {
  89564. function GLTFFileLoader() {
  89565. // #region Common options
  89566. /**
  89567. * Raised when the asset has been parsed.
  89568. * The data.json property stores the glTF JSON.
  89569. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89570. */
  89571. this.onParsedObservable = new BABYLON.Observable();
  89572. // #endregion
  89573. // #region V2 options
  89574. /**
  89575. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89576. */
  89577. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89578. /**
  89579. * The animation start mode (NONE, FIRST, ALL).
  89580. */
  89581. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89582. /**
  89583. * Set to true to compile materials before raising the success callback.
  89584. */
  89585. this.compileMaterials = false;
  89586. /**
  89587. * Set to true to also compile materials with clip planes.
  89588. */
  89589. this.useClipPlane = false;
  89590. /**
  89591. * Set to true to compile shadow generators before raising the success callback.
  89592. */
  89593. this.compileShadowGenerators = false;
  89594. /**
  89595. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89596. */
  89597. this.onMeshLoadedObservable = new BABYLON.Observable();
  89598. /**
  89599. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89600. */
  89601. this.onTextureLoadedObservable = new BABYLON.Observable();
  89602. /**
  89603. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89604. */
  89605. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89606. /**
  89607. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89608. * For assets with LODs, raised when all of the LODs are complete.
  89609. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89610. */
  89611. this.onCompleteObservable = new BABYLON.Observable();
  89612. /**
  89613. * Raised when the loader is disposed.
  89614. */
  89615. this.onDisposeObservable = new BABYLON.Observable();
  89616. /**
  89617. * Raised after a loader extension is created.
  89618. * Set additional options for a loader extension in this event.
  89619. */
  89620. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89621. // #endregion
  89622. this._loader = null;
  89623. this.name = "gltf";
  89624. this.extensions = {
  89625. ".gltf": { isBinary: false },
  89626. ".glb": { isBinary: true }
  89627. };
  89628. }
  89629. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89630. set: function (callback) {
  89631. if (this._onParsedObserver) {
  89632. this.onParsedObservable.remove(this._onParsedObserver);
  89633. }
  89634. this._onParsedObserver = this.onParsedObservable.add(callback);
  89635. },
  89636. enumerable: true,
  89637. configurable: true
  89638. });
  89639. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89640. set: function (callback) {
  89641. if (this._onMeshLoadedObserver) {
  89642. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89643. }
  89644. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89645. },
  89646. enumerable: true,
  89647. configurable: true
  89648. });
  89649. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89650. set: function (callback) {
  89651. if (this._onTextureLoadedObserver) {
  89652. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89653. }
  89654. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89655. },
  89656. enumerable: true,
  89657. configurable: true
  89658. });
  89659. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89660. set: function (callback) {
  89661. if (this._onMaterialLoadedObserver) {
  89662. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89663. }
  89664. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89665. },
  89666. enumerable: true,
  89667. configurable: true
  89668. });
  89669. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89670. set: function (callback) {
  89671. if (this._onCompleteObserver) {
  89672. this.onCompleteObservable.remove(this._onCompleteObserver);
  89673. }
  89674. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89675. },
  89676. enumerable: true,
  89677. configurable: true
  89678. });
  89679. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89680. set: function (callback) {
  89681. if (this._onDisposeObserver) {
  89682. this.onDisposeObservable.remove(this._onDisposeObserver);
  89683. }
  89684. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89685. },
  89686. enumerable: true,
  89687. configurable: true
  89688. });
  89689. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89690. set: function (callback) {
  89691. if (this._onExtensionLoadedObserver) {
  89692. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89693. }
  89694. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89695. },
  89696. enumerable: true,
  89697. configurable: true
  89698. });
  89699. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89700. /**
  89701. * The loader state or null if not active.
  89702. */
  89703. get: function () {
  89704. return this._loader ? this._loader.state : null;
  89705. },
  89706. enumerable: true,
  89707. configurable: true
  89708. });
  89709. /**
  89710. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89711. */
  89712. GLTFFileLoader.prototype.dispose = function () {
  89713. if (this._loader) {
  89714. this._loader.dispose();
  89715. this._loader = null;
  89716. }
  89717. this.onMeshLoadedObservable.clear();
  89718. this.onTextureLoadedObservable.clear();
  89719. this.onMaterialLoadedObservable.clear();
  89720. this.onDisposeObservable.notifyObservers(this);
  89721. this.onDisposeObservable.clear();
  89722. };
  89723. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89724. var _this = this;
  89725. return Promise.resolve().then(function () {
  89726. var loaderData = _this._parse(data);
  89727. _this._loader = _this._getLoader(loaderData);
  89728. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89729. });
  89730. };
  89731. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89732. var _this = this;
  89733. return Promise.resolve().then(function () {
  89734. var loaderData = _this._parse(data);
  89735. _this._loader = _this._getLoader(loaderData);
  89736. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89737. });
  89738. };
  89739. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89740. var _this = this;
  89741. return Promise.resolve().then(function () {
  89742. var loaderData = _this._parse(data);
  89743. _this._loader = _this._getLoader(loaderData);
  89744. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89745. var container = new BABYLON.AssetContainer(scene);
  89746. Array.prototype.push.apply(container.meshes, result.meshes);
  89747. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89748. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89749. container.removeAllFromScene();
  89750. return container;
  89751. });
  89752. });
  89753. };
  89754. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  89755. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  89756. };
  89757. GLTFFileLoader.prototype.createPlugin = function () {
  89758. return new GLTFFileLoader();
  89759. };
  89760. GLTFFileLoader.prototype._parse = function (data) {
  89761. var parsedData;
  89762. if (data instanceof ArrayBuffer) {
  89763. parsedData = GLTFFileLoader._parseBinary(data);
  89764. }
  89765. else {
  89766. parsedData = {
  89767. json: JSON.parse(data),
  89768. bin: null
  89769. };
  89770. }
  89771. this.onParsedObservable.notifyObservers(parsedData);
  89772. this.onParsedObservable.clear();
  89773. return parsedData;
  89774. };
  89775. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  89776. var _this = this;
  89777. var loaderVersion = { major: 2, minor: 0 };
  89778. var asset = loaderData.json.asset || {};
  89779. var version = GLTFFileLoader._parseVersion(asset.version);
  89780. if (!version) {
  89781. throw new Error("Invalid version: " + asset.version);
  89782. }
  89783. if (asset.minVersion !== undefined) {
  89784. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  89785. if (!minVersion) {
  89786. throw new Error("Invalid minimum version: " + asset.minVersion);
  89787. }
  89788. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  89789. throw new Error("Incompatible minimum version: " + asset.minVersion);
  89790. }
  89791. }
  89792. var createLoaders = {
  89793. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  89794. 2: GLTFFileLoader.CreateGLTFLoaderV2
  89795. };
  89796. var createLoader = createLoaders[version.major];
  89797. if (!createLoader) {
  89798. throw new Error("Unsupported version: " + asset.version);
  89799. }
  89800. var loader = createLoader();
  89801. loader.coordinateSystemMode = this.coordinateSystemMode;
  89802. loader.animationStartMode = this.animationStartMode;
  89803. loader.compileMaterials = this.compileMaterials;
  89804. loader.useClipPlane = this.useClipPlane;
  89805. loader.compileShadowGenerators = this.compileShadowGenerators;
  89806. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  89807. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  89808. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  89809. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  89810. loader.onCompleteObservable.add(function () {
  89811. _this.onMeshLoadedObservable.clear();
  89812. _this.onTextureLoadedObservable.clear();
  89813. _this.onMaterialLoadedObservable.clear();
  89814. _this.onCompleteObservable.notifyObservers(_this);
  89815. _this.onCompleteObservable.clear();
  89816. });
  89817. return loader;
  89818. };
  89819. GLTFFileLoader._parseBinary = function (data) {
  89820. var Binary = {
  89821. Magic: 0x46546C67
  89822. };
  89823. var binaryReader = new BinaryReader(data);
  89824. var magic = binaryReader.readUint32();
  89825. if (magic !== Binary.Magic) {
  89826. throw new Error("Unexpected magic: " + magic);
  89827. }
  89828. var version = binaryReader.readUint32();
  89829. switch (version) {
  89830. case 1: return GLTFFileLoader._parseV1(binaryReader);
  89831. case 2: return GLTFFileLoader._parseV2(binaryReader);
  89832. }
  89833. throw new Error("Unsupported version: " + version);
  89834. };
  89835. GLTFFileLoader._parseV1 = function (binaryReader) {
  89836. var ContentFormat = {
  89837. JSON: 0
  89838. };
  89839. var length = binaryReader.readUint32();
  89840. if (length != binaryReader.getLength()) {
  89841. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89842. }
  89843. var contentLength = binaryReader.readUint32();
  89844. var contentFormat = binaryReader.readUint32();
  89845. var content;
  89846. switch (contentFormat) {
  89847. case ContentFormat.JSON: {
  89848. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  89849. break;
  89850. }
  89851. default: {
  89852. throw new Error("Unexpected content format: " + contentFormat);
  89853. }
  89854. }
  89855. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  89856. var body = binaryReader.readUint8Array(bytesRemaining);
  89857. return {
  89858. json: content,
  89859. bin: body
  89860. };
  89861. };
  89862. GLTFFileLoader._parseV2 = function (binaryReader) {
  89863. var ChunkFormat = {
  89864. JSON: 0x4E4F534A,
  89865. BIN: 0x004E4942
  89866. };
  89867. var length = binaryReader.readUint32();
  89868. if (length !== binaryReader.getLength()) {
  89869. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89870. }
  89871. // JSON chunk
  89872. var chunkLength = binaryReader.readUint32();
  89873. var chunkFormat = binaryReader.readUint32();
  89874. if (chunkFormat !== ChunkFormat.JSON) {
  89875. throw new Error("First chunk format is not JSON");
  89876. }
  89877. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  89878. // Look for BIN chunk
  89879. var bin = null;
  89880. while (binaryReader.getPosition() < binaryReader.getLength()) {
  89881. var chunkLength_1 = binaryReader.readUint32();
  89882. var chunkFormat_1 = binaryReader.readUint32();
  89883. switch (chunkFormat_1) {
  89884. case ChunkFormat.JSON: {
  89885. throw new Error("Unexpected JSON chunk");
  89886. }
  89887. case ChunkFormat.BIN: {
  89888. bin = binaryReader.readUint8Array(chunkLength_1);
  89889. break;
  89890. }
  89891. default: {
  89892. // ignore unrecognized chunkFormat
  89893. binaryReader.skipBytes(chunkLength_1);
  89894. break;
  89895. }
  89896. }
  89897. }
  89898. return {
  89899. json: json,
  89900. bin: bin
  89901. };
  89902. };
  89903. GLTFFileLoader._parseVersion = function (version) {
  89904. if (version === "1.0" || version === "1.0.1") {
  89905. return {
  89906. major: 1,
  89907. minor: 0
  89908. };
  89909. }
  89910. var match = (version + "").match(/^(\d+)\.(\d+)/);
  89911. if (!match) {
  89912. return null;
  89913. }
  89914. return {
  89915. major: parseInt(match[1]),
  89916. minor: parseInt(match[2])
  89917. };
  89918. };
  89919. GLTFFileLoader._compareVersion = function (a, b) {
  89920. if (a.major > b.major)
  89921. return 1;
  89922. if (a.major < b.major)
  89923. return -1;
  89924. if (a.minor > b.minor)
  89925. return 1;
  89926. if (a.minor < b.minor)
  89927. return -1;
  89928. return 0;
  89929. };
  89930. GLTFFileLoader._decodeBufferToText = function (buffer) {
  89931. var result = "";
  89932. var length = buffer.byteLength;
  89933. for (var i = 0; i < length; i++) {
  89934. result += String.fromCharCode(buffer[i]);
  89935. }
  89936. return result;
  89937. };
  89938. // #endregion
  89939. // #region V1 options
  89940. GLTFFileLoader.IncrementalLoading = true;
  89941. GLTFFileLoader.HomogeneousCoordinates = false;
  89942. return GLTFFileLoader;
  89943. }());
  89944. BABYLON.GLTFFileLoader = GLTFFileLoader;
  89945. var BinaryReader = /** @class */ (function () {
  89946. function BinaryReader(arrayBuffer) {
  89947. this._arrayBuffer = arrayBuffer;
  89948. this._dataView = new DataView(arrayBuffer);
  89949. this._byteOffset = 0;
  89950. }
  89951. BinaryReader.prototype.getPosition = function () {
  89952. return this._byteOffset;
  89953. };
  89954. BinaryReader.prototype.getLength = function () {
  89955. return this._arrayBuffer.byteLength;
  89956. };
  89957. BinaryReader.prototype.readUint32 = function () {
  89958. var value = this._dataView.getUint32(this._byteOffset, true);
  89959. this._byteOffset += 4;
  89960. return value;
  89961. };
  89962. BinaryReader.prototype.readUint8Array = function (length) {
  89963. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  89964. this._byteOffset += length;
  89965. return value;
  89966. };
  89967. BinaryReader.prototype.skipBytes = function (length) {
  89968. this._byteOffset += length;
  89969. };
  89970. return BinaryReader;
  89971. }());
  89972. if (BABYLON.SceneLoader) {
  89973. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  89974. }
  89975. })(BABYLON || (BABYLON = {}));
  89976. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  89977. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89978. var BABYLON;
  89979. (function (BABYLON) {
  89980. var GLTF1;
  89981. (function (GLTF1) {
  89982. /**
  89983. * Enums
  89984. */
  89985. var EComponentType;
  89986. (function (EComponentType) {
  89987. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89988. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89989. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89990. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89991. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89992. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  89993. var EShaderType;
  89994. (function (EShaderType) {
  89995. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  89996. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  89997. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  89998. var EParameterType;
  89999. (function (EParameterType) {
  90000. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90001. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90002. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90003. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90004. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90005. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90006. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90007. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90008. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90009. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90010. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90011. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90012. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90013. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90014. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90015. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90016. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90017. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90018. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90019. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90020. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90021. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90022. var ETextureWrapMode;
  90023. (function (ETextureWrapMode) {
  90024. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90025. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90026. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90027. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90028. var ETextureFilterType;
  90029. (function (ETextureFilterType) {
  90030. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90031. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90032. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90033. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90034. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90035. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90036. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90037. var ETextureFormat;
  90038. (function (ETextureFormat) {
  90039. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90040. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90041. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90042. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90043. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90044. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90045. var ECullingType;
  90046. (function (ECullingType) {
  90047. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90048. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90049. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90050. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90051. var EBlendingFunction;
  90052. (function (EBlendingFunction) {
  90053. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90054. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90055. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90056. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90057. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90058. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90059. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90060. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90061. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90062. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90063. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90064. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90065. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90066. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90067. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90068. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90069. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90070. })(BABYLON || (BABYLON = {}));
  90071. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90072. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90073. var BABYLON;
  90074. (function (BABYLON) {
  90075. var GLTF1;
  90076. (function (GLTF1) {
  90077. /**
  90078. * Tokenizer. Used for shaders compatibility
  90079. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90080. */
  90081. var ETokenType;
  90082. (function (ETokenType) {
  90083. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90084. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90085. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90086. })(ETokenType || (ETokenType = {}));
  90087. var Tokenizer = /** @class */ (function () {
  90088. function Tokenizer(toParse) {
  90089. this._pos = 0;
  90090. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90091. this._toParse = toParse;
  90092. this._maxPos = toParse.length;
  90093. }
  90094. Tokenizer.prototype.getNextToken = function () {
  90095. if (this.isEnd())
  90096. return ETokenType.END_OF_INPUT;
  90097. this.currentString = this.read();
  90098. this.currentToken = ETokenType.UNKNOWN;
  90099. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90100. this.currentToken = ETokenType.IDENTIFIER;
  90101. this.currentIdentifier = this.currentString;
  90102. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90103. this.currentIdentifier += this.currentString;
  90104. this.forward();
  90105. }
  90106. }
  90107. return this.currentToken;
  90108. };
  90109. Tokenizer.prototype.peek = function () {
  90110. return this._toParse[this._pos];
  90111. };
  90112. Tokenizer.prototype.read = function () {
  90113. return this._toParse[this._pos++];
  90114. };
  90115. Tokenizer.prototype.forward = function () {
  90116. this._pos++;
  90117. };
  90118. Tokenizer.prototype.isEnd = function () {
  90119. return this._pos >= this._maxPos;
  90120. };
  90121. return Tokenizer;
  90122. }());
  90123. /**
  90124. * Values
  90125. */
  90126. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90127. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90128. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90129. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90130. /**
  90131. * Parse
  90132. */
  90133. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90134. for (var buf in parsedBuffers) {
  90135. var parsedBuffer = parsedBuffers[buf];
  90136. gltfRuntime.buffers[buf] = parsedBuffer;
  90137. gltfRuntime.buffersCount++;
  90138. }
  90139. };
  90140. var parseShaders = function (parsedShaders, gltfRuntime) {
  90141. for (var sha in parsedShaders) {
  90142. var parsedShader = parsedShaders[sha];
  90143. gltfRuntime.shaders[sha] = parsedShader;
  90144. gltfRuntime.shaderscount++;
  90145. }
  90146. };
  90147. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90148. for (var object in parsedObjects) {
  90149. var parsedObject = parsedObjects[object];
  90150. gltfRuntime[runtimeProperty][object] = parsedObject;
  90151. }
  90152. };
  90153. /**
  90154. * Utils
  90155. */
  90156. var normalizeUVs = function (buffer) {
  90157. if (!buffer) {
  90158. return;
  90159. }
  90160. for (var i = 0; i < buffer.length / 2; i++) {
  90161. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90162. }
  90163. };
  90164. var getAttribute = function (attributeParameter) {
  90165. if (attributeParameter.semantic === "NORMAL") {
  90166. return "normal";
  90167. }
  90168. else if (attributeParameter.semantic === "POSITION") {
  90169. return "position";
  90170. }
  90171. else if (attributeParameter.semantic === "JOINT") {
  90172. return "matricesIndices";
  90173. }
  90174. else if (attributeParameter.semantic === "WEIGHT") {
  90175. return "matricesWeights";
  90176. }
  90177. else if (attributeParameter.semantic === "COLOR") {
  90178. return "color";
  90179. }
  90180. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90181. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90182. return "uv" + (channel === 0 ? "" : channel + 1);
  90183. }
  90184. return null;
  90185. };
  90186. /**
  90187. * Loads and creates animations
  90188. */
  90189. var loadAnimations = function (gltfRuntime) {
  90190. for (var anim in gltfRuntime.animations) {
  90191. var animation = gltfRuntime.animations[anim];
  90192. if (!animation.channels || !animation.samplers) {
  90193. continue;
  90194. }
  90195. var lastAnimation = null;
  90196. for (var i = 0; i < animation.channels.length; i++) {
  90197. // Get parameters and load buffers
  90198. var channel = animation.channels[i];
  90199. var sampler = animation.samplers[channel.sampler];
  90200. if (!sampler) {
  90201. continue;
  90202. }
  90203. var inputData = null;
  90204. var outputData = null;
  90205. if (animation.parameters) {
  90206. inputData = animation.parameters[sampler.input];
  90207. outputData = animation.parameters[sampler.output];
  90208. }
  90209. else {
  90210. inputData = sampler.input;
  90211. outputData = sampler.output;
  90212. }
  90213. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90214. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90215. var targetID = channel.target.id;
  90216. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90217. if (targetNode === null) {
  90218. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90219. }
  90220. if (targetNode === null) {
  90221. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90222. continue;
  90223. }
  90224. var isBone = targetNode instanceof BABYLON.Bone;
  90225. // Get target path (position, rotation or scaling)
  90226. var targetPath = channel.target.path;
  90227. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90228. if (targetPathIndex !== -1) {
  90229. targetPath = babylonAnimationPaths[targetPathIndex];
  90230. }
  90231. // Determine animation type
  90232. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90233. if (!isBone) {
  90234. if (targetPath === "rotationQuaternion") {
  90235. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90236. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90237. }
  90238. else {
  90239. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90240. }
  90241. }
  90242. // Create animation and key frames
  90243. var babylonAnimation = null;
  90244. var keys = [];
  90245. var arrayOffset = 0;
  90246. var modifyKey = false;
  90247. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90248. babylonAnimation = lastAnimation;
  90249. modifyKey = true;
  90250. }
  90251. if (!modifyKey) {
  90252. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90253. }
  90254. // For each frame
  90255. for (var j = 0; j < bufferInput.length; j++) {
  90256. var value = null;
  90257. if (targetPath === "rotationQuaternion") {
  90258. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90259. arrayOffset += 4;
  90260. }
  90261. else {
  90262. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90263. arrayOffset += 3;
  90264. }
  90265. if (isBone) {
  90266. var bone = targetNode;
  90267. var translation = BABYLON.Vector3.Zero();
  90268. var rotationQuaternion = new BABYLON.Quaternion();
  90269. var scaling = BABYLON.Vector3.Zero();
  90270. // Warning on decompose
  90271. var mat = bone.getBaseMatrix();
  90272. if (modifyKey && lastAnimation) {
  90273. mat = lastAnimation.getKeys()[j].value;
  90274. }
  90275. mat.decompose(scaling, rotationQuaternion, translation);
  90276. if (targetPath === "position") {
  90277. translation = value;
  90278. }
  90279. else if (targetPath === "rotationQuaternion") {
  90280. rotationQuaternion = value;
  90281. }
  90282. else {
  90283. scaling = value;
  90284. }
  90285. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90286. }
  90287. if (!modifyKey) {
  90288. keys.push({
  90289. frame: bufferInput[j],
  90290. value: value
  90291. });
  90292. }
  90293. else if (lastAnimation) {
  90294. lastAnimation.getKeys()[j].value = value;
  90295. }
  90296. }
  90297. // Finish
  90298. if (!modifyKey && babylonAnimation) {
  90299. babylonAnimation.setKeys(keys);
  90300. targetNode.animations.push(babylonAnimation);
  90301. }
  90302. lastAnimation = babylonAnimation;
  90303. gltfRuntime.scene.stopAnimation(targetNode);
  90304. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90305. }
  90306. }
  90307. };
  90308. /**
  90309. * Returns the bones transformation matrix
  90310. */
  90311. var configureBoneTransformation = function (node) {
  90312. var mat = null;
  90313. if (node.translation || node.rotation || node.scale) {
  90314. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90315. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90316. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90317. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90318. }
  90319. else {
  90320. mat = BABYLON.Matrix.FromArray(node.matrix);
  90321. }
  90322. return mat;
  90323. };
  90324. /**
  90325. * Returns the parent bone
  90326. */
  90327. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90328. // Try to find
  90329. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90330. if (newSkeleton.bones[i].name === jointName) {
  90331. return newSkeleton.bones[i];
  90332. }
  90333. }
  90334. // Not found, search in gltf nodes
  90335. var nodes = gltfRuntime.nodes;
  90336. for (var nde in nodes) {
  90337. var node = nodes[nde];
  90338. if (!node.jointName) {
  90339. continue;
  90340. }
  90341. var children = node.children;
  90342. for (var i = 0; i < children.length; i++) {
  90343. var child = gltfRuntime.nodes[children[i]];
  90344. if (!child.jointName) {
  90345. continue;
  90346. }
  90347. if (child.jointName === jointName) {
  90348. var mat = configureBoneTransformation(node);
  90349. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90350. bone.id = nde;
  90351. return bone;
  90352. }
  90353. }
  90354. }
  90355. return null;
  90356. };
  90357. /**
  90358. * Returns the appropriate root node
  90359. */
  90360. var getNodeToRoot = function (nodesToRoot, id) {
  90361. for (var i = 0; i < nodesToRoot.length; i++) {
  90362. var nodeToRoot = nodesToRoot[i];
  90363. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90364. var child = nodeToRoot.node.children[j];
  90365. if (child === id) {
  90366. return nodeToRoot.bone;
  90367. }
  90368. }
  90369. }
  90370. return null;
  90371. };
  90372. /**
  90373. * Returns the node with the joint name
  90374. */
  90375. var getJointNode = function (gltfRuntime, jointName) {
  90376. var nodes = gltfRuntime.nodes;
  90377. var node = nodes[jointName];
  90378. if (node) {
  90379. return {
  90380. node: node,
  90381. id: jointName
  90382. };
  90383. }
  90384. for (var nde in nodes) {
  90385. node = nodes[nde];
  90386. if (node.jointName === jointName) {
  90387. return {
  90388. node: node,
  90389. id: nde
  90390. };
  90391. }
  90392. }
  90393. return null;
  90394. };
  90395. /**
  90396. * Checks if a nodes is in joints
  90397. */
  90398. var nodeIsInJoints = function (skins, id) {
  90399. for (var i = 0; i < skins.jointNames.length; i++) {
  90400. if (skins.jointNames[i] === id) {
  90401. return true;
  90402. }
  90403. }
  90404. return false;
  90405. };
  90406. /**
  90407. * Fills the nodes to root for bones and builds hierarchy
  90408. */
  90409. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90410. // Creates nodes for root
  90411. for (var nde in gltfRuntime.nodes) {
  90412. var node = gltfRuntime.nodes[nde];
  90413. var id = nde;
  90414. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90415. continue;
  90416. }
  90417. // Create node to root bone
  90418. var mat = configureBoneTransformation(node);
  90419. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90420. bone.id = id;
  90421. nodesToRoot.push({ bone: bone, node: node, id: id });
  90422. }
  90423. // Parenting
  90424. for (var i = 0; i < nodesToRoot.length; i++) {
  90425. var nodeToRoot = nodesToRoot[i];
  90426. var children = nodeToRoot.node.children;
  90427. for (var j = 0; j < children.length; j++) {
  90428. var child = null;
  90429. for (var k = 0; k < nodesToRoot.length; k++) {
  90430. if (nodesToRoot[k].id === children[j]) {
  90431. child = nodesToRoot[k];
  90432. break;
  90433. }
  90434. }
  90435. if (child) {
  90436. child.bone._parent = nodeToRoot.bone;
  90437. nodeToRoot.bone.children.push(child.bone);
  90438. }
  90439. }
  90440. }
  90441. };
  90442. /**
  90443. * Imports a skeleton
  90444. */
  90445. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90446. if (!newSkeleton) {
  90447. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90448. }
  90449. if (!skins.babylonSkeleton) {
  90450. return newSkeleton;
  90451. }
  90452. // Find the root bones
  90453. var nodesToRoot = [];
  90454. var nodesToRootToAdd = [];
  90455. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90456. newSkeleton.bones = [];
  90457. // Joints
  90458. for (var i = 0; i < skins.jointNames.length; i++) {
  90459. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90460. if (!jointNode) {
  90461. continue;
  90462. }
  90463. var node = jointNode.node;
  90464. if (!node) {
  90465. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90466. continue;
  90467. }
  90468. var id = jointNode.id;
  90469. // Optimize, if the bone already exists...
  90470. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90471. if (existingBone) {
  90472. newSkeleton.bones.push(existingBone);
  90473. continue;
  90474. }
  90475. // Search for parent bone
  90476. var foundBone = false;
  90477. var parentBone = null;
  90478. for (var j = 0; j < i; j++) {
  90479. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90480. if (!jointNode_1) {
  90481. continue;
  90482. }
  90483. var joint = jointNode_1.node;
  90484. if (!joint) {
  90485. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90486. continue;
  90487. }
  90488. var children = joint.children;
  90489. if (!children) {
  90490. continue;
  90491. }
  90492. foundBone = false;
  90493. for (var k = 0; k < children.length; k++) {
  90494. if (children[k] === id) {
  90495. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90496. foundBone = true;
  90497. break;
  90498. }
  90499. }
  90500. if (foundBone) {
  90501. break;
  90502. }
  90503. }
  90504. // Create bone
  90505. var mat = configureBoneTransformation(node);
  90506. if (!parentBone && nodesToRoot.length > 0) {
  90507. parentBone = getNodeToRoot(nodesToRoot, id);
  90508. if (parentBone) {
  90509. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90510. nodesToRootToAdd.push(parentBone);
  90511. }
  90512. }
  90513. }
  90514. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90515. bone.id = id;
  90516. }
  90517. // Polish
  90518. var bones = newSkeleton.bones;
  90519. newSkeleton.bones = [];
  90520. for (var i = 0; i < skins.jointNames.length; i++) {
  90521. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90522. if (!jointNode) {
  90523. continue;
  90524. }
  90525. for (var j = 0; j < bones.length; j++) {
  90526. if (bones[j].id === jointNode.id) {
  90527. newSkeleton.bones.push(bones[j]);
  90528. break;
  90529. }
  90530. }
  90531. }
  90532. newSkeleton.prepare();
  90533. // Finish
  90534. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90535. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90536. }
  90537. return newSkeleton;
  90538. };
  90539. /**
  90540. * Imports a mesh and its geometries
  90541. */
  90542. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90543. if (!newMesh) {
  90544. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90545. newMesh.id = id;
  90546. }
  90547. if (!node.babylonNode) {
  90548. return newMesh;
  90549. }
  90550. var subMaterials = [];
  90551. var vertexData = null;
  90552. var verticesStarts = new Array();
  90553. var verticesCounts = new Array();
  90554. var indexStarts = new Array();
  90555. var indexCounts = new Array();
  90556. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90557. var meshID = meshes[meshIndex];
  90558. var mesh = gltfRuntime.meshes[meshID];
  90559. if (!mesh) {
  90560. continue;
  90561. }
  90562. // Positions, normals and UVs
  90563. for (var i = 0; i < mesh.primitives.length; i++) {
  90564. // Temporary vertex data
  90565. var tempVertexData = new BABYLON.VertexData();
  90566. var primitive = mesh.primitives[i];
  90567. if (primitive.mode !== 4) {
  90568. // continue;
  90569. }
  90570. var attributes = primitive.attributes;
  90571. var accessor = null;
  90572. var buffer = null;
  90573. // Set positions, normal and uvs
  90574. for (var semantic in attributes) {
  90575. // Link accessor and buffer view
  90576. accessor = gltfRuntime.accessors[attributes[semantic]];
  90577. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90578. if (semantic === "NORMAL") {
  90579. tempVertexData.normals = new Float32Array(buffer.length);
  90580. tempVertexData.normals.set(buffer);
  90581. }
  90582. else if (semantic === "POSITION") {
  90583. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90584. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90585. for (var j = 0; j < buffer.length; j += 4) {
  90586. tempVertexData.positions[j] = buffer[j];
  90587. tempVertexData.positions[j + 1] = buffer[j + 1];
  90588. tempVertexData.positions[j + 2] = buffer[j + 2];
  90589. }
  90590. }
  90591. else {
  90592. tempVertexData.positions = new Float32Array(buffer.length);
  90593. tempVertexData.positions.set(buffer);
  90594. }
  90595. verticesCounts.push(tempVertexData.positions.length);
  90596. }
  90597. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90598. var channel = Number(semantic.split("_")[1]);
  90599. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90600. var uvs = new Float32Array(buffer.length);
  90601. uvs.set(buffer);
  90602. normalizeUVs(uvs);
  90603. tempVertexData.set(uvs, uvKind);
  90604. }
  90605. else if (semantic === "JOINT") {
  90606. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90607. tempVertexData.matricesIndices.set(buffer);
  90608. }
  90609. else if (semantic === "WEIGHT") {
  90610. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90611. tempVertexData.matricesWeights.set(buffer);
  90612. }
  90613. else if (semantic === "COLOR") {
  90614. tempVertexData.colors = new Float32Array(buffer.length);
  90615. tempVertexData.colors.set(buffer);
  90616. }
  90617. }
  90618. // Indices
  90619. accessor = gltfRuntime.accessors[primitive.indices];
  90620. if (accessor) {
  90621. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90622. tempVertexData.indices = new Int32Array(buffer.length);
  90623. tempVertexData.indices.set(buffer);
  90624. indexCounts.push(tempVertexData.indices.length);
  90625. }
  90626. else {
  90627. // Set indices on the fly
  90628. var indices = [];
  90629. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90630. indices.push(j);
  90631. }
  90632. tempVertexData.indices = new Int32Array(indices);
  90633. indexCounts.push(tempVertexData.indices.length);
  90634. }
  90635. if (!vertexData) {
  90636. vertexData = tempVertexData;
  90637. }
  90638. else {
  90639. vertexData.merge(tempVertexData);
  90640. }
  90641. // Sub material
  90642. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90643. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90644. // Update vertices start and index start
  90645. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90646. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90647. }
  90648. }
  90649. var material;
  90650. if (subMaterials.length > 1) {
  90651. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90652. material.subMaterials = subMaterials;
  90653. }
  90654. else {
  90655. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90656. }
  90657. if (subMaterials.length === 1) {
  90658. material = subMaterials[0];
  90659. }
  90660. if (!newMesh.material) {
  90661. newMesh.material = material;
  90662. }
  90663. // Apply geometry
  90664. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90665. newMesh.computeWorldMatrix(true);
  90666. // Apply submeshes
  90667. newMesh.subMeshes = [];
  90668. var index = 0;
  90669. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90670. var meshID = meshes[meshIndex];
  90671. var mesh = gltfRuntime.meshes[meshID];
  90672. if (!mesh) {
  90673. continue;
  90674. }
  90675. for (var i = 0; i < mesh.primitives.length; i++) {
  90676. if (mesh.primitives[i].mode !== 4) {
  90677. //continue;
  90678. }
  90679. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90680. index++;
  90681. }
  90682. }
  90683. // Finish
  90684. return newMesh;
  90685. };
  90686. /**
  90687. * Configure node transformation from position, rotation and scaling
  90688. */
  90689. var configureNode = function (newNode, position, rotation, scaling) {
  90690. if (newNode.position) {
  90691. newNode.position = position;
  90692. }
  90693. if (newNode.rotationQuaternion || newNode.rotation) {
  90694. newNode.rotationQuaternion = rotation;
  90695. }
  90696. if (newNode.scaling) {
  90697. newNode.scaling = scaling;
  90698. }
  90699. };
  90700. /**
  90701. * Configures node from transformation matrix
  90702. */
  90703. var configureNodeFromMatrix = function (newNode, node, parent) {
  90704. if (node.matrix) {
  90705. var position = new BABYLON.Vector3(0, 0, 0);
  90706. var rotation = new BABYLON.Quaternion();
  90707. var scaling = new BABYLON.Vector3(0, 0, 0);
  90708. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90709. mat.decompose(scaling, rotation, position);
  90710. configureNode(newNode, position, rotation, scaling);
  90711. }
  90712. else if (node.translation && node.rotation && node.scale) {
  90713. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90714. }
  90715. newNode.computeWorldMatrix(true);
  90716. };
  90717. /**
  90718. * Imports a node
  90719. */
  90720. var importNode = function (gltfRuntime, node, id, parent) {
  90721. var lastNode = null;
  90722. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90723. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90724. return null;
  90725. }
  90726. }
  90727. // Meshes
  90728. if (node.skin) {
  90729. if (node.meshes) {
  90730. var skin = gltfRuntime.skins[node.skin];
  90731. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90732. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90733. if (newMesh.skeleton === null) {
  90734. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90735. if (!skin.babylonSkeleton) {
  90736. skin.babylonSkeleton = newMesh.skeleton;
  90737. }
  90738. }
  90739. lastNode = newMesh;
  90740. }
  90741. }
  90742. else if (node.meshes) {
  90743. /**
  90744. * Improve meshes property
  90745. */
  90746. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90747. lastNode = newMesh;
  90748. }
  90749. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90750. var light = gltfRuntime.lights[node.light];
  90751. if (light) {
  90752. if (light.type === "ambient") {
  90753. var ambienLight = light[light.type];
  90754. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90755. hemiLight.name = node.name || "";
  90756. if (ambienLight.color) {
  90757. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  90758. }
  90759. lastNode = hemiLight;
  90760. }
  90761. else if (light.type === "directional") {
  90762. var directionalLight = light[light.type];
  90763. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90764. dirLight.name = node.name || "";
  90765. if (directionalLight.color) {
  90766. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  90767. }
  90768. lastNode = dirLight;
  90769. }
  90770. else if (light.type === "point") {
  90771. var pointLight = light[light.type];
  90772. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90773. ptLight.name = node.name || "";
  90774. if (pointLight.color) {
  90775. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  90776. }
  90777. lastNode = ptLight;
  90778. }
  90779. else if (light.type === "spot") {
  90780. var spotLight = light[light.type];
  90781. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  90782. spLight.name = node.name || "";
  90783. if (spotLight.color) {
  90784. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  90785. }
  90786. if (spotLight.fallOfAngle) {
  90787. spLight.angle = spotLight.fallOfAngle;
  90788. }
  90789. if (spotLight.fallOffExponent) {
  90790. spLight.exponent = spotLight.fallOffExponent;
  90791. }
  90792. lastNode = spLight;
  90793. }
  90794. }
  90795. }
  90796. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90797. var camera = gltfRuntime.cameras[node.camera];
  90798. if (camera) {
  90799. if (camera.type === "orthographic") {
  90800. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90801. orthoCamera.name = node.name || "";
  90802. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  90803. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90804. lastNode = orthoCamera;
  90805. }
  90806. else if (camera.type === "perspective") {
  90807. var perspectiveCamera = camera[camera.type];
  90808. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90809. persCamera.name = node.name || "";
  90810. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90811. if (!perspectiveCamera.aspectRatio) {
  90812. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  90813. }
  90814. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  90815. persCamera.maxZ = perspectiveCamera.zfar;
  90816. persCamera.minZ = perspectiveCamera.znear;
  90817. }
  90818. lastNode = persCamera;
  90819. }
  90820. }
  90821. }
  90822. // Empty node
  90823. if (!node.jointName) {
  90824. if (node.babylonNode) {
  90825. return node.babylonNode;
  90826. }
  90827. else if (lastNode === null) {
  90828. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90829. node.babylonNode = dummy;
  90830. lastNode = dummy;
  90831. }
  90832. }
  90833. if (lastNode !== null) {
  90834. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  90835. configureNodeFromMatrix(lastNode, node, parent);
  90836. }
  90837. else {
  90838. var translation = node.translation || [0, 0, 0];
  90839. var rotation = node.rotation || [0, 0, 0, 1];
  90840. var scale = node.scale || [1, 1, 1];
  90841. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  90842. }
  90843. lastNode.updateCache(true);
  90844. node.babylonNode = lastNode;
  90845. }
  90846. return lastNode;
  90847. };
  90848. /**
  90849. * Traverses nodes and creates them
  90850. */
  90851. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  90852. if (meshIncluded === void 0) { meshIncluded = false; }
  90853. var node = gltfRuntime.nodes[id];
  90854. var newNode = null;
  90855. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  90856. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  90857. meshIncluded = true;
  90858. }
  90859. else {
  90860. meshIncluded = false;
  90861. }
  90862. }
  90863. else {
  90864. meshIncluded = true;
  90865. }
  90866. if (!node.jointName && meshIncluded) {
  90867. newNode = importNode(gltfRuntime, node, id, parent);
  90868. if (newNode !== null) {
  90869. newNode.id = id;
  90870. newNode.parent = parent;
  90871. }
  90872. }
  90873. if (node.children) {
  90874. for (var i = 0; i < node.children.length; i++) {
  90875. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  90876. }
  90877. }
  90878. };
  90879. /**
  90880. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  90881. */
  90882. var postLoad = function (gltfRuntime) {
  90883. // Nodes
  90884. var currentScene = gltfRuntime.currentScene;
  90885. if (currentScene) {
  90886. for (var i = 0; i < currentScene.nodes.length; i++) {
  90887. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90888. }
  90889. }
  90890. else {
  90891. for (var thing in gltfRuntime.scenes) {
  90892. currentScene = gltfRuntime.scenes[thing];
  90893. for (var i = 0; i < currentScene.nodes.length; i++) {
  90894. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90895. }
  90896. }
  90897. }
  90898. // Set animations
  90899. loadAnimations(gltfRuntime);
  90900. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  90901. var skeleton = gltfRuntime.scene.skeletons[i];
  90902. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  90903. }
  90904. };
  90905. /**
  90906. * onBind shaderrs callback to set uniforms and matrices
  90907. */
  90908. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  90909. var materialValues = material.values || technique.parameters;
  90910. for (var unif in unTreatedUniforms) {
  90911. var uniform = unTreatedUniforms[unif];
  90912. var type = uniform.type;
  90913. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  90914. if (uniform.semantic && !uniform.source && !uniform.node) {
  90915. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  90916. }
  90917. else if (uniform.semantic && (uniform.source || uniform.node)) {
  90918. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  90919. if (source === null) {
  90920. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  90921. }
  90922. if (source === null) {
  90923. continue;
  90924. }
  90925. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  90926. }
  90927. }
  90928. else {
  90929. var value = materialValues[technique.uniforms[unif]];
  90930. if (!value) {
  90931. continue;
  90932. }
  90933. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90934. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  90935. if (texture === null || texture === undefined) {
  90936. continue;
  90937. }
  90938. shaderMaterial.getEffect().setTexture(unif, texture);
  90939. }
  90940. else {
  90941. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  90942. }
  90943. }
  90944. }
  90945. onSuccess(shaderMaterial);
  90946. };
  90947. /**
  90948. * Prepare uniforms to send the only one time
  90949. * Loads the appropriate textures
  90950. */
  90951. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  90952. var materialValues = material.values || technique.parameters;
  90953. var techniqueUniforms = technique.uniforms;
  90954. /**
  90955. * Prepare values here (not matrices)
  90956. */
  90957. for (var unif in unTreatedUniforms) {
  90958. var uniform = unTreatedUniforms[unif];
  90959. var type = uniform.type;
  90960. var value = materialValues[techniqueUniforms[unif]];
  90961. if (value === undefined) {
  90962. // In case the value is the same for all materials
  90963. value = uniform.value;
  90964. }
  90965. if (!value) {
  90966. continue;
  90967. }
  90968. var onLoadTexture = function (uniformName) {
  90969. return function (texture) {
  90970. if (uniform.value && uniformName) {
  90971. // Static uniform
  90972. shaderMaterial.setTexture(uniformName, texture);
  90973. delete unTreatedUniforms[uniformName];
  90974. }
  90975. };
  90976. };
  90977. // Texture (sampler2D)
  90978. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90979. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  90980. }
  90981. else {
  90982. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  90983. // Static uniform
  90984. delete unTreatedUniforms[unif];
  90985. }
  90986. }
  90987. }
  90988. };
  90989. /**
  90990. * Shader compilation failed
  90991. */
  90992. var onShaderCompileError = function (program, shaderMaterial, onError) {
  90993. return function (effect, error) {
  90994. shaderMaterial.dispose(true);
  90995. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  90996. };
  90997. };
  90998. /**
  90999. * Shader compilation success
  91000. */
  91001. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91002. return function (_) {
  91003. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91004. shaderMaterial.onBind = function (mesh) {
  91005. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91006. };
  91007. };
  91008. };
  91009. /**
  91010. * Returns the appropriate uniform if already handled by babylon
  91011. */
  91012. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91013. for (var unif in technique.uniforms) {
  91014. var uniform = technique.uniforms[unif];
  91015. var uniformParameter = technique.parameters[uniform];
  91016. if (tokenizer.currentIdentifier === unif) {
  91017. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91018. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91019. if (transformIndex !== -1) {
  91020. delete unTreatedUniforms[unif];
  91021. return babylonTransforms[transformIndex];
  91022. }
  91023. }
  91024. }
  91025. }
  91026. return tokenizer.currentIdentifier;
  91027. };
  91028. /**
  91029. * All shaders loaded. Create materials one by one
  91030. */
  91031. var importMaterials = function (gltfRuntime) {
  91032. // Create materials
  91033. for (var mat in gltfRuntime.materials) {
  91034. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91035. }
  91036. };
  91037. /**
  91038. * Implementation of the base glTF spec
  91039. */
  91040. var GLTFLoaderBase = /** @class */ (function () {
  91041. function GLTFLoaderBase() {
  91042. }
  91043. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91044. var gltfRuntime = {
  91045. extensions: {},
  91046. accessors: {},
  91047. buffers: {},
  91048. bufferViews: {},
  91049. meshes: {},
  91050. lights: {},
  91051. cameras: {},
  91052. nodes: {},
  91053. images: {},
  91054. textures: {},
  91055. shaders: {},
  91056. programs: {},
  91057. samplers: {},
  91058. techniques: {},
  91059. materials: {},
  91060. animations: {},
  91061. skins: {},
  91062. extensionsUsed: [],
  91063. scenes: {},
  91064. buffersCount: 0,
  91065. shaderscount: 0,
  91066. scene: scene,
  91067. rootUrl: rootUrl,
  91068. loadedBufferCount: 0,
  91069. loadedBufferViews: {},
  91070. loadedShaderCount: 0,
  91071. importOnlyMeshes: false,
  91072. dummyNodes: []
  91073. };
  91074. // Parse
  91075. if (parsedData.extensions) {
  91076. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91077. }
  91078. if (parsedData.extensionsUsed) {
  91079. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91080. }
  91081. if (parsedData.buffers) {
  91082. parseBuffers(parsedData.buffers, gltfRuntime);
  91083. }
  91084. if (parsedData.bufferViews) {
  91085. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91086. }
  91087. if (parsedData.accessors) {
  91088. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91089. }
  91090. if (parsedData.meshes) {
  91091. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91092. }
  91093. if (parsedData.lights) {
  91094. parseObject(parsedData.lights, "lights", gltfRuntime);
  91095. }
  91096. if (parsedData.cameras) {
  91097. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91098. }
  91099. if (parsedData.nodes) {
  91100. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91101. }
  91102. if (parsedData.images) {
  91103. parseObject(parsedData.images, "images", gltfRuntime);
  91104. }
  91105. if (parsedData.textures) {
  91106. parseObject(parsedData.textures, "textures", gltfRuntime);
  91107. }
  91108. if (parsedData.shaders) {
  91109. parseShaders(parsedData.shaders, gltfRuntime);
  91110. }
  91111. if (parsedData.programs) {
  91112. parseObject(parsedData.programs, "programs", gltfRuntime);
  91113. }
  91114. if (parsedData.samplers) {
  91115. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91116. }
  91117. if (parsedData.techniques) {
  91118. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91119. }
  91120. if (parsedData.materials) {
  91121. parseObject(parsedData.materials, "materials", gltfRuntime);
  91122. }
  91123. if (parsedData.animations) {
  91124. parseObject(parsedData.animations, "animations", gltfRuntime);
  91125. }
  91126. if (parsedData.skins) {
  91127. parseObject(parsedData.skins, "skins", gltfRuntime);
  91128. }
  91129. if (parsedData.scenes) {
  91130. gltfRuntime.scenes = parsedData.scenes;
  91131. }
  91132. if (parsedData.scene && parsedData.scenes) {
  91133. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91134. }
  91135. return gltfRuntime;
  91136. };
  91137. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91138. var buffer = gltfRuntime.buffers[id];
  91139. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91140. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91141. }
  91142. else {
  91143. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91144. if (request) {
  91145. onError(request.status + " " + request.statusText);
  91146. }
  91147. });
  91148. }
  91149. };
  91150. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91151. var texture = gltfRuntime.textures[id];
  91152. if (!texture || !texture.source) {
  91153. onError("");
  91154. return;
  91155. }
  91156. if (texture.babylonTexture) {
  91157. onSuccess(null);
  91158. return;
  91159. }
  91160. var source = gltfRuntime.images[texture.source];
  91161. if (BABYLON.Tools.IsBase64(source.uri)) {
  91162. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91163. }
  91164. else {
  91165. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91166. if (request) {
  91167. onError(request.status + " " + request.statusText);
  91168. }
  91169. });
  91170. }
  91171. };
  91172. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91173. var texture = gltfRuntime.textures[id];
  91174. if (texture.babylonTexture) {
  91175. onSuccess(texture.babylonTexture);
  91176. return;
  91177. }
  91178. var sampler = gltfRuntime.samplers[texture.sampler];
  91179. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91180. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91181. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91182. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91183. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91184. var blob = new Blob([buffer]);
  91185. var blobURL = URL.createObjectURL(blob);
  91186. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91187. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91188. if (sampler.wrapS !== undefined) {
  91189. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91190. }
  91191. if (sampler.wrapT !== undefined) {
  91192. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91193. }
  91194. newTexture.name = id;
  91195. texture.babylonTexture = newTexture;
  91196. onSuccess(newTexture);
  91197. };
  91198. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91199. var shader = gltfRuntime.shaders[id];
  91200. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91201. var shaderString = atob(shader.uri.split(",")[1]);
  91202. onSuccess(shaderString);
  91203. }
  91204. else {
  91205. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91206. if (request) {
  91207. onError(request.status + " " + request.statusText);
  91208. }
  91209. });
  91210. }
  91211. };
  91212. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91213. var material = gltfRuntime.materials[id];
  91214. if (!material.technique) {
  91215. if (onError) {
  91216. onError("No technique found.");
  91217. }
  91218. return;
  91219. }
  91220. var technique = gltfRuntime.techniques[material.technique];
  91221. if (!technique) {
  91222. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91223. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91224. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91225. onSuccess(defaultMaterial);
  91226. return;
  91227. }
  91228. var program = gltfRuntime.programs[technique.program];
  91229. var states = technique.states;
  91230. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91231. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91232. var newVertexShader = "";
  91233. var newPixelShader = "";
  91234. var vertexTokenizer = new Tokenizer(vertexShader);
  91235. var pixelTokenizer = new Tokenizer(pixelShader);
  91236. var unTreatedUniforms = {};
  91237. var uniforms = [];
  91238. var attributes = [];
  91239. var samplers = [];
  91240. // Fill uniform, sampler2D and attributes
  91241. for (var unif in technique.uniforms) {
  91242. var uniform = technique.uniforms[unif];
  91243. var uniformParameter = technique.parameters[uniform];
  91244. unTreatedUniforms[unif] = uniformParameter;
  91245. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91246. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91247. if (transformIndex !== -1) {
  91248. uniforms.push(babylonTransforms[transformIndex]);
  91249. delete unTreatedUniforms[unif];
  91250. }
  91251. else {
  91252. uniforms.push(unif);
  91253. }
  91254. }
  91255. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91256. samplers.push(unif);
  91257. }
  91258. else {
  91259. uniforms.push(unif);
  91260. }
  91261. }
  91262. for (var attr in technique.attributes) {
  91263. var attribute = technique.attributes[attr];
  91264. var attributeParameter = technique.parameters[attribute];
  91265. if (attributeParameter.semantic) {
  91266. attributes.push(getAttribute(attributeParameter));
  91267. }
  91268. }
  91269. // Configure vertex shader
  91270. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91271. var tokenType = vertexTokenizer.currentToken;
  91272. if (tokenType !== ETokenType.IDENTIFIER) {
  91273. newVertexShader += vertexTokenizer.currentString;
  91274. continue;
  91275. }
  91276. var foundAttribute = false;
  91277. for (var attr in technique.attributes) {
  91278. var attribute = technique.attributes[attr];
  91279. var attributeParameter = technique.parameters[attribute];
  91280. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91281. newVertexShader += getAttribute(attributeParameter);
  91282. foundAttribute = true;
  91283. break;
  91284. }
  91285. }
  91286. if (foundAttribute) {
  91287. continue;
  91288. }
  91289. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91290. }
  91291. // Configure pixel shader
  91292. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91293. var tokenType = pixelTokenizer.currentToken;
  91294. if (tokenType !== ETokenType.IDENTIFIER) {
  91295. newPixelShader += pixelTokenizer.currentString;
  91296. continue;
  91297. }
  91298. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91299. }
  91300. // Create shader material
  91301. var shaderPath = {
  91302. vertex: program.vertexShader + id,
  91303. fragment: program.fragmentShader + id
  91304. };
  91305. var options = {
  91306. attributes: attributes,
  91307. uniforms: uniforms,
  91308. samplers: samplers,
  91309. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91310. };
  91311. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91312. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91313. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91314. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91315. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91316. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91317. if (states && states.functions) {
  91318. var functions = states.functions;
  91319. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91320. shaderMaterial.backFaceCulling = false;
  91321. }
  91322. var blendFunc = functions.blendFuncSeparate;
  91323. if (blendFunc) {
  91324. 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) {
  91325. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91326. }
  91327. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91328. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91329. }
  91330. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91331. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91332. }
  91333. 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) {
  91334. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91335. }
  91336. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91337. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91338. }
  91339. 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) {
  91340. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91341. }
  91342. }
  91343. }
  91344. };
  91345. return GLTFLoaderBase;
  91346. }());
  91347. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91348. /**
  91349. * glTF V1 Loader
  91350. */
  91351. var GLTFLoader = /** @class */ (function () {
  91352. function GLTFLoader() {
  91353. // #region Stubs for IGLTFLoader interface
  91354. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91355. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91356. this.compileMaterials = false;
  91357. this.useClipPlane = false;
  91358. this.compileShadowGenerators = false;
  91359. this.onDisposeObservable = new BABYLON.Observable();
  91360. this.onMeshLoadedObservable = new BABYLON.Observable();
  91361. this.onTextureLoadedObservable = new BABYLON.Observable();
  91362. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91363. this.onCompleteObservable = new BABYLON.Observable();
  91364. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91365. this.state = null;
  91366. }
  91367. GLTFLoader.RegisterExtension = function (extension) {
  91368. if (GLTFLoader.Extensions[extension.name]) {
  91369. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91370. return;
  91371. }
  91372. GLTFLoader.Extensions[extension.name] = extension;
  91373. };
  91374. GLTFLoader.prototype.dispose = function () { };
  91375. // #endregion
  91376. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91377. var _this = this;
  91378. scene.useRightHandedSystem = true;
  91379. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91380. gltfRuntime.importOnlyMeshes = true;
  91381. if (meshesNames === "") {
  91382. gltfRuntime.importMeshesNames = [];
  91383. }
  91384. else if (typeof meshesNames === "string") {
  91385. gltfRuntime.importMeshesNames = [meshesNames];
  91386. }
  91387. else if (meshesNames && !(meshesNames instanceof Array)) {
  91388. gltfRuntime.importMeshesNames = [meshesNames];
  91389. }
  91390. else {
  91391. gltfRuntime.importMeshesNames = [];
  91392. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91393. }
  91394. // Create nodes
  91395. _this._createNodes(gltfRuntime);
  91396. var meshes = new Array();
  91397. var skeletons = new Array();
  91398. // Fill arrays of meshes and skeletons
  91399. for (var nde in gltfRuntime.nodes) {
  91400. var node = gltfRuntime.nodes[nde];
  91401. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91402. meshes.push(node.babylonNode);
  91403. }
  91404. }
  91405. for (var skl in gltfRuntime.skins) {
  91406. var skin = gltfRuntime.skins[skl];
  91407. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91408. skeletons.push(skin.babylonSkeleton);
  91409. }
  91410. }
  91411. // Load buffers, shaders, materials, etc.
  91412. _this._loadBuffersAsync(gltfRuntime, function () {
  91413. _this._loadShadersAsync(gltfRuntime, function () {
  91414. importMaterials(gltfRuntime);
  91415. postLoad(gltfRuntime);
  91416. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91417. onSuccess(meshes, [], skeletons);
  91418. }
  91419. });
  91420. }, onProgress);
  91421. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91422. onSuccess(meshes, [], skeletons);
  91423. }
  91424. }, onError);
  91425. return true;
  91426. };
  91427. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91428. var _this = this;
  91429. return new Promise(function (resolve, reject) {
  91430. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91431. resolve({
  91432. meshes: meshes,
  91433. particleSystems: particleSystems,
  91434. skeletons: skeletons
  91435. });
  91436. }, onProgress, function (message) {
  91437. reject(new Error(message));
  91438. });
  91439. });
  91440. };
  91441. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91442. var _this = this;
  91443. scene.useRightHandedSystem = true;
  91444. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91445. // Load runtime extensios
  91446. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91447. // Create nodes
  91448. _this._createNodes(gltfRuntime);
  91449. // Load buffers, shaders, materials, etc.
  91450. _this._loadBuffersAsync(gltfRuntime, function () {
  91451. _this._loadShadersAsync(gltfRuntime, function () {
  91452. importMaterials(gltfRuntime);
  91453. postLoad(gltfRuntime);
  91454. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91455. onSuccess();
  91456. }
  91457. });
  91458. });
  91459. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91460. onSuccess();
  91461. }
  91462. }, onError);
  91463. }, onError);
  91464. };
  91465. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91466. var _this = this;
  91467. return new Promise(function (resolve, reject) {
  91468. _this._loadAsync(scene, data, rootUrl, function () {
  91469. resolve();
  91470. }, onProgress, function (message) {
  91471. reject(new Error(message));
  91472. });
  91473. });
  91474. };
  91475. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91476. var hasShaders = false;
  91477. var processShader = function (sha, shader) {
  91478. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91479. gltfRuntime.loadedShaderCount++;
  91480. if (shaderString) {
  91481. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91482. }
  91483. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91484. onload();
  91485. }
  91486. }, function () {
  91487. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91488. });
  91489. };
  91490. for (var sha in gltfRuntime.shaders) {
  91491. hasShaders = true;
  91492. var shader = gltfRuntime.shaders[sha];
  91493. if (shader) {
  91494. processShader.bind(this, sha, shader)();
  91495. }
  91496. else {
  91497. BABYLON.Tools.Error("No shader named: " + sha);
  91498. }
  91499. }
  91500. if (!hasShaders) {
  91501. onload();
  91502. }
  91503. };
  91504. ;
  91505. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91506. var hasBuffers = false;
  91507. var processBuffer = function (buf, buffer) {
  91508. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91509. gltfRuntime.loadedBufferCount++;
  91510. if (bufferView) {
  91511. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91512. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91513. }
  91514. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91515. }
  91516. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91517. onLoad();
  91518. }
  91519. }, function () {
  91520. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91521. });
  91522. };
  91523. for (var buf in gltfRuntime.buffers) {
  91524. hasBuffers = true;
  91525. var buffer = gltfRuntime.buffers[buf];
  91526. if (buffer) {
  91527. processBuffer.bind(this, buf, buffer)();
  91528. }
  91529. else {
  91530. BABYLON.Tools.Error("No buffer named: " + buf);
  91531. }
  91532. }
  91533. if (!hasBuffers) {
  91534. onLoad();
  91535. }
  91536. };
  91537. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91538. var currentScene = gltfRuntime.currentScene;
  91539. if (currentScene) {
  91540. // Only one scene even if multiple scenes are defined
  91541. for (var i = 0; i < currentScene.nodes.length; i++) {
  91542. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91543. }
  91544. }
  91545. else {
  91546. // Load all scenes
  91547. for (var thing in gltfRuntime.scenes) {
  91548. currentScene = gltfRuntime.scenes[thing];
  91549. for (var i = 0; i < currentScene.nodes.length; i++) {
  91550. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91551. }
  91552. }
  91553. }
  91554. };
  91555. GLTFLoader.Extensions = {};
  91556. return GLTFLoader;
  91557. }());
  91558. GLTF1.GLTFLoader = GLTFLoader;
  91559. ;
  91560. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91561. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91562. })(BABYLON || (BABYLON = {}));
  91563. //# sourceMappingURL=babylon.glTFLoader.js.map
  91564. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91565. var BABYLON;
  91566. (function (BABYLON) {
  91567. var GLTF1;
  91568. (function (GLTF1) {
  91569. /**
  91570. * Utils functions for GLTF
  91571. */
  91572. var GLTFUtils = /** @class */ (function () {
  91573. function GLTFUtils() {
  91574. }
  91575. /**
  91576. * Sets the given "parameter" matrix
  91577. * @param scene: the {BABYLON.Scene} object
  91578. * @param source: the source node where to pick the matrix
  91579. * @param parameter: the GLTF technique parameter
  91580. * @param uniformName: the name of the shader's uniform
  91581. * @param shaderMaterial: the shader material
  91582. */
  91583. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91584. var mat = null;
  91585. if (parameter.semantic === "MODEL") {
  91586. mat = source.getWorldMatrix();
  91587. }
  91588. else if (parameter.semantic === "PROJECTION") {
  91589. mat = scene.getProjectionMatrix();
  91590. }
  91591. else if (parameter.semantic === "VIEW") {
  91592. mat = scene.getViewMatrix();
  91593. }
  91594. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91595. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91596. }
  91597. else if (parameter.semantic === "MODELVIEW") {
  91598. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91599. }
  91600. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91601. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91602. }
  91603. else if (parameter.semantic === "MODELINVERSE") {
  91604. mat = source.getWorldMatrix().invert();
  91605. }
  91606. else if (parameter.semantic === "VIEWINVERSE") {
  91607. mat = scene.getViewMatrix().invert();
  91608. }
  91609. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91610. mat = scene.getProjectionMatrix().invert();
  91611. }
  91612. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91613. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91614. }
  91615. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91616. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91617. }
  91618. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91619. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91620. }
  91621. else {
  91622. debugger;
  91623. }
  91624. if (mat) {
  91625. switch (parameter.type) {
  91626. case GLTF1.EParameterType.FLOAT_MAT2:
  91627. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91628. break;
  91629. case GLTF1.EParameterType.FLOAT_MAT3:
  91630. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91631. break;
  91632. case GLTF1.EParameterType.FLOAT_MAT4:
  91633. shaderMaterial.setMatrix(uniformName, mat);
  91634. break;
  91635. default: break;
  91636. }
  91637. }
  91638. };
  91639. /**
  91640. * Sets the given "parameter" matrix
  91641. * @param shaderMaterial: the shader material
  91642. * @param uniform: the name of the shader's uniform
  91643. * @param value: the value of the uniform
  91644. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91645. */
  91646. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91647. switch (type) {
  91648. case GLTF1.EParameterType.FLOAT:
  91649. shaderMaterial.setFloat(uniform, value);
  91650. return true;
  91651. case GLTF1.EParameterType.FLOAT_VEC2:
  91652. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91653. return true;
  91654. case GLTF1.EParameterType.FLOAT_VEC3:
  91655. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91656. return true;
  91657. case GLTF1.EParameterType.FLOAT_VEC4:
  91658. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91659. return true;
  91660. default: return false;
  91661. }
  91662. };
  91663. /**
  91664. * Returns the wrap mode of the texture
  91665. * @param mode: the mode value
  91666. */
  91667. GLTFUtils.GetWrapMode = function (mode) {
  91668. switch (mode) {
  91669. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91670. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91671. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91672. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91673. }
  91674. };
  91675. /**
  91676. * Returns the byte stride giving an accessor
  91677. * @param accessor: the GLTF accessor objet
  91678. */
  91679. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91680. // Needs this function since "byteStride" isn't requiered in glTF format
  91681. var type = accessor.type;
  91682. switch (type) {
  91683. case "VEC2": return 2;
  91684. case "VEC3": return 3;
  91685. case "VEC4": return 4;
  91686. case "MAT2": return 4;
  91687. case "MAT3": return 9;
  91688. case "MAT4": return 16;
  91689. default: return 1;
  91690. }
  91691. };
  91692. /**
  91693. * Returns the texture filter mode giving a mode value
  91694. * @param mode: the filter mode value
  91695. */
  91696. GLTFUtils.GetTextureFilterMode = function (mode) {
  91697. switch (mode) {
  91698. case GLTF1.ETextureFilterType.LINEAR:
  91699. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91700. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91701. case GLTF1.ETextureFilterType.NEAREST:
  91702. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91703. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91704. }
  91705. };
  91706. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91707. var byteOffset = bufferView.byteOffset + byteOffset;
  91708. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91709. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91710. throw new Error("Buffer access is out of range");
  91711. }
  91712. var buffer = loadedBufferView.buffer;
  91713. byteOffset += loadedBufferView.byteOffset;
  91714. switch (componentType) {
  91715. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91716. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91717. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91718. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91719. default: return new Float32Array(buffer, byteOffset, byteLength);
  91720. }
  91721. };
  91722. /**
  91723. * Returns a buffer from its accessor
  91724. * @param gltfRuntime: the GLTF runtime
  91725. * @param accessor: the GLTF accessor
  91726. */
  91727. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91728. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91729. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91730. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91731. };
  91732. /**
  91733. * Decodes a buffer view into a string
  91734. * @param view: the buffer view
  91735. */
  91736. GLTFUtils.DecodeBufferToText = function (view) {
  91737. var result = "";
  91738. var length = view.byteLength;
  91739. for (var i = 0; i < length; ++i) {
  91740. result += String.fromCharCode(view[i]);
  91741. }
  91742. return result;
  91743. };
  91744. /**
  91745. * Returns the default material of gltf. Related to
  91746. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91747. * @param scene: the Babylon.js scene
  91748. */
  91749. GLTFUtils.GetDefaultMaterial = function (scene) {
  91750. if (!GLTFUtils._DefaultMaterial) {
  91751. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  91752. "precision highp float;",
  91753. "",
  91754. "uniform mat4 worldView;",
  91755. "uniform mat4 projection;",
  91756. "",
  91757. "attribute vec3 position;",
  91758. "",
  91759. "void main(void)",
  91760. "{",
  91761. " gl_Position = projection * worldView * vec4(position, 1.0);",
  91762. "}"
  91763. ].join("\n");
  91764. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  91765. "precision highp float;",
  91766. "",
  91767. "uniform vec4 u_emission;",
  91768. "",
  91769. "void main(void)",
  91770. "{",
  91771. " gl_FragColor = u_emission;",
  91772. "}"
  91773. ].join("\n");
  91774. var shaderPath = {
  91775. vertex: "GLTFDefaultMaterial",
  91776. fragment: "GLTFDefaultMaterial"
  91777. };
  91778. var options = {
  91779. attributes: ["position"],
  91780. uniforms: ["worldView", "projection", "u_emission"],
  91781. samplers: new Array(),
  91782. needAlphaBlending: false
  91783. };
  91784. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  91785. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  91786. }
  91787. return GLTFUtils._DefaultMaterial;
  91788. };
  91789. // The GLTF default material
  91790. GLTFUtils._DefaultMaterial = null;
  91791. return GLTFUtils;
  91792. }());
  91793. GLTF1.GLTFUtils = GLTFUtils;
  91794. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91795. })(BABYLON || (BABYLON = {}));
  91796. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91797. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91798. var BABYLON;
  91799. (function (BABYLON) {
  91800. var GLTF1;
  91801. (function (GLTF1) {
  91802. var GLTFLoaderExtension = /** @class */ (function () {
  91803. function GLTFLoaderExtension(name) {
  91804. this._name = name;
  91805. }
  91806. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  91807. get: function () {
  91808. return this._name;
  91809. },
  91810. enumerable: true,
  91811. configurable: true
  91812. });
  91813. /**
  91814. * Defines an override for loading the runtime
  91815. * Return true to stop further extensions from loading the runtime
  91816. */
  91817. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91818. return false;
  91819. };
  91820. /**
  91821. * Defines an onverride for creating gltf runtime
  91822. * Return true to stop further extensions from creating the runtime
  91823. */
  91824. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91825. return false;
  91826. };
  91827. /**
  91828. * Defines an override for loading buffers
  91829. * Return true to stop further extensions from loading this buffer
  91830. */
  91831. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91832. return false;
  91833. };
  91834. /**
  91835. * Defines an override for loading texture buffers
  91836. * Return true to stop further extensions from loading this texture data
  91837. */
  91838. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91839. return false;
  91840. };
  91841. /**
  91842. * Defines an override for creating textures
  91843. * Return true to stop further extensions from loading this texture
  91844. */
  91845. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91846. return false;
  91847. };
  91848. /**
  91849. * Defines an override for loading shader strings
  91850. * Return true to stop further extensions from loading this shader data
  91851. */
  91852. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91853. return false;
  91854. };
  91855. /**
  91856. * Defines an override for loading materials
  91857. * Return true to stop further extensions from loading this material
  91858. */
  91859. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91860. return false;
  91861. };
  91862. // ---------
  91863. // Utilities
  91864. // ---------
  91865. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91866. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91867. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  91868. }, function () {
  91869. setTimeout(function () {
  91870. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91871. });
  91872. });
  91873. };
  91874. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91875. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91876. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  91877. }, function () {
  91878. setTimeout(function () {
  91879. onSuccess();
  91880. });
  91881. });
  91882. };
  91883. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91884. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91885. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91886. }, function () {
  91887. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91888. });
  91889. };
  91890. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  91891. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  91892. };
  91893. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91894. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91895. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91896. }, function () {
  91897. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91898. });
  91899. };
  91900. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91901. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91902. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91903. }, function () {
  91904. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91905. });
  91906. };
  91907. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91908. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91909. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91910. }, function () {
  91911. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91912. });
  91913. };
  91914. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91915. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91916. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91917. }, function () {
  91918. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91919. });
  91920. };
  91921. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  91922. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  91923. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  91924. if (func(loaderExtension)) {
  91925. return;
  91926. }
  91927. }
  91928. defaultFunc();
  91929. };
  91930. return GLTFLoaderExtension;
  91931. }());
  91932. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  91933. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91934. })(BABYLON || (BABYLON = {}));
  91935. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91936. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91937. var BABYLON;
  91938. (function (BABYLON) {
  91939. var GLTF1;
  91940. (function (GLTF1) {
  91941. var BinaryExtensionBufferName = "binary_glTF";
  91942. ;
  91943. ;
  91944. var GLTFBinaryExtension = /** @class */ (function (_super) {
  91945. __extends(GLTFBinaryExtension, _super);
  91946. function GLTFBinaryExtension() {
  91947. return _super.call(this, "KHR_binary_glTF") || this;
  91948. }
  91949. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91950. var extensionsUsed = data.json.extensionsUsed;
  91951. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  91952. return false;
  91953. }
  91954. this._bin = data.bin;
  91955. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91956. return true;
  91957. };
  91958. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91959. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  91960. return false;
  91961. }
  91962. if (id !== BinaryExtensionBufferName) {
  91963. return false;
  91964. }
  91965. onSuccess(this._bin);
  91966. return true;
  91967. };
  91968. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91969. var texture = gltfRuntime.textures[id];
  91970. var source = gltfRuntime.images[texture.source];
  91971. if (!source.extensions || !(this.name in source.extensions)) {
  91972. return false;
  91973. }
  91974. var sourceExt = source.extensions[this.name];
  91975. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  91976. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91977. onSuccess(buffer);
  91978. return true;
  91979. };
  91980. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91981. var shader = gltfRuntime.shaders[id];
  91982. if (!shader.extensions || !(this.name in shader.extensions)) {
  91983. return false;
  91984. }
  91985. var binaryExtensionShader = shader.extensions[this.name];
  91986. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  91987. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91988. setTimeout(function () {
  91989. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  91990. onSuccess(shaderString);
  91991. });
  91992. return true;
  91993. };
  91994. return GLTFBinaryExtension;
  91995. }(GLTF1.GLTFLoaderExtension));
  91996. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  91997. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  91998. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91999. })(BABYLON || (BABYLON = {}));
  92000. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92001. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92002. var BABYLON;
  92003. (function (BABYLON) {
  92004. var GLTF1;
  92005. (function (GLTF1) {
  92006. ;
  92007. ;
  92008. ;
  92009. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92010. __extends(GLTFMaterialsCommonExtension, _super);
  92011. function GLTFMaterialsCommonExtension() {
  92012. return _super.call(this, "KHR_materials_common") || this;
  92013. }
  92014. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92015. if (!gltfRuntime.extensions)
  92016. return false;
  92017. var extension = gltfRuntime.extensions[this.name];
  92018. if (!extension)
  92019. return false;
  92020. // Create lights
  92021. var lights = extension.lights;
  92022. if (lights) {
  92023. for (var thing in lights) {
  92024. var light = lights[thing];
  92025. switch (light.type) {
  92026. case "ambient":
  92027. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92028. var ambient = light.ambient;
  92029. if (ambient) {
  92030. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92031. }
  92032. break;
  92033. case "point":
  92034. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92035. var point = light.point;
  92036. if (point) {
  92037. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92038. }
  92039. break;
  92040. case "directional":
  92041. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92042. var directional = light.directional;
  92043. if (directional) {
  92044. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92045. }
  92046. break;
  92047. case "spot":
  92048. var spot = light.spot;
  92049. if (spot) {
  92050. 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);
  92051. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92052. }
  92053. break;
  92054. default:
  92055. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92056. break;
  92057. }
  92058. }
  92059. }
  92060. return false;
  92061. };
  92062. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92063. var material = gltfRuntime.materials[id];
  92064. if (!material || !material.extensions)
  92065. return false;
  92066. var extension = material.extensions[this.name];
  92067. if (!extension)
  92068. return false;
  92069. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92070. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92071. if (extension.technique === "CONSTANT") {
  92072. standardMaterial.disableLighting = true;
  92073. }
  92074. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92075. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92076. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92077. // Ambient
  92078. if (typeof extension.values.ambient === "string") {
  92079. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92080. }
  92081. else {
  92082. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92083. }
  92084. // Diffuse
  92085. if (typeof extension.values.diffuse === "string") {
  92086. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92087. }
  92088. else {
  92089. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92090. }
  92091. // Emission
  92092. if (typeof extension.values.emission === "string") {
  92093. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92094. }
  92095. else {
  92096. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92097. }
  92098. // Specular
  92099. if (typeof extension.values.specular === "string") {
  92100. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92101. }
  92102. else {
  92103. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92104. }
  92105. return true;
  92106. };
  92107. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92108. // Create buffer from texture url
  92109. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92110. // Create texture from buffer
  92111. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92112. }, onError);
  92113. };
  92114. return GLTFMaterialsCommonExtension;
  92115. }(GLTF1.GLTFLoaderExtension));
  92116. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92117. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92118. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92119. })(BABYLON || (BABYLON = {}));
  92120. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92121. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92122. var BABYLON;
  92123. (function (BABYLON) {
  92124. var GLTF2;
  92125. (function (GLTF2) {
  92126. var ArrayItem = /** @class */ (function () {
  92127. function ArrayItem() {
  92128. }
  92129. ArrayItem.Assign = function (values) {
  92130. if (values) {
  92131. for (var index = 0; index < values.length; index++) {
  92132. values[index]._index = index;
  92133. }
  92134. }
  92135. };
  92136. return ArrayItem;
  92137. }());
  92138. GLTF2.ArrayItem = ArrayItem;
  92139. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92140. })(BABYLON || (BABYLON = {}));
  92141. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92142. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92143. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92144. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92145. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92146. var BABYLON;
  92147. (function (BABYLON) {
  92148. var GLTF2;
  92149. (function (GLTF2) {
  92150. var GLTFLoader = /** @class */ (function () {
  92151. function GLTFLoader() {
  92152. this._completePromises = new Array();
  92153. this._disposed = false;
  92154. this._state = null;
  92155. this._extensions = {};
  92156. this._defaultSampler = {};
  92157. this._requests = new Array();
  92158. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92159. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92160. this.compileMaterials = false;
  92161. this.useClipPlane = false;
  92162. this.compileShadowGenerators = false;
  92163. this.onDisposeObservable = new BABYLON.Observable();
  92164. this.onMeshLoadedObservable = new BABYLON.Observable();
  92165. this.onTextureLoadedObservable = new BABYLON.Observable();
  92166. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92167. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92168. this.onCompleteObservable = new BABYLON.Observable();
  92169. }
  92170. GLTFLoader._Register = function (name, factory) {
  92171. if (GLTFLoader._Factories[name]) {
  92172. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92173. return;
  92174. }
  92175. GLTFLoader._Factories[name] = factory;
  92176. // Keep the order of registration so that extensions registered first are called first.
  92177. GLTFLoader._Names.push(name);
  92178. };
  92179. Object.defineProperty(GLTFLoader.prototype, "state", {
  92180. get: function () {
  92181. return this._state;
  92182. },
  92183. enumerable: true,
  92184. configurable: true
  92185. });
  92186. GLTFLoader.prototype.dispose = function () {
  92187. if (this._disposed) {
  92188. return;
  92189. }
  92190. this._disposed = true;
  92191. this.onDisposeObservable.notifyObservers(this);
  92192. this.onDisposeObservable.clear();
  92193. this._clear();
  92194. };
  92195. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92196. var _this = this;
  92197. return Promise.resolve().then(function () {
  92198. var nodes = null;
  92199. if (meshesNames) {
  92200. var nodeMap_1 = {};
  92201. if (_this._gltf.nodes) {
  92202. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92203. var node = _a[_i];
  92204. if (node.name) {
  92205. nodeMap_1[node.name] = node;
  92206. }
  92207. }
  92208. }
  92209. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92210. nodes = names.map(function (name) {
  92211. var node = nodeMap_1[name];
  92212. if (!node) {
  92213. throw new Error("Failed to find node " + name);
  92214. }
  92215. return node;
  92216. });
  92217. }
  92218. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92219. return {
  92220. meshes: _this._getMeshes(),
  92221. particleSystems: [],
  92222. skeletons: _this._getSkeletons(),
  92223. };
  92224. });
  92225. });
  92226. };
  92227. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92228. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92229. };
  92230. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92231. var _this = this;
  92232. return Promise.resolve().then(function () {
  92233. _this._loadExtensions();
  92234. _this._babylonScene = scene;
  92235. _this._rootUrl = rootUrl;
  92236. _this._progressCallback = onProgress;
  92237. _this._state = BABYLON.GLTFLoaderState.Loading;
  92238. _this._loadData(data);
  92239. _this._checkExtensions();
  92240. var promises = new Array();
  92241. if (nodes) {
  92242. promises.push(_this._loadNodesAsync(nodes));
  92243. }
  92244. else {
  92245. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92246. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92247. }
  92248. if (_this.compileMaterials) {
  92249. promises.push(_this._compileMaterialsAsync());
  92250. }
  92251. if (_this.compileShadowGenerators) {
  92252. promises.push(_this._compileShadowGeneratorsAsync());
  92253. }
  92254. return Promise.all(promises).then(function () {
  92255. _this._state = BABYLON.GLTFLoaderState.Ready;
  92256. _this._startAnimations();
  92257. BABYLON.Tools.SetImmediate(function () {
  92258. if (!_this._disposed) {
  92259. Promise.all(_this._completePromises).then(function () {
  92260. _this._state = BABYLON.GLTFLoaderState.Complete;
  92261. _this.onCompleteObservable.notifyObservers(_this);
  92262. _this.onCompleteObservable.clear();
  92263. _this._clear();
  92264. }).catch(function (error) {
  92265. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92266. _this._clear();
  92267. });
  92268. }
  92269. });
  92270. });
  92271. }).catch(function (error) {
  92272. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92273. _this._clear();
  92274. throw error;
  92275. });
  92276. };
  92277. GLTFLoader.prototype._loadExtensions = function () {
  92278. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92279. var name_1 = _a[_i];
  92280. var extension = GLTFLoader._Factories[name_1](this);
  92281. this._extensions[name_1] = extension;
  92282. this.onExtensionLoadedObservable.notifyObservers(extension);
  92283. }
  92284. this.onExtensionLoadedObservable.clear();
  92285. };
  92286. GLTFLoader.prototype._loadData = function (data) {
  92287. this._gltf = data.json;
  92288. this._setupData();
  92289. if (data.bin) {
  92290. var buffers = this._gltf.buffers;
  92291. if (buffers && buffers[0] && !buffers[0].uri) {
  92292. var binaryBuffer = buffers[0];
  92293. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92294. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92295. }
  92296. binaryBuffer._data = Promise.resolve(data.bin);
  92297. }
  92298. else {
  92299. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92300. }
  92301. }
  92302. };
  92303. GLTFLoader.prototype._setupData = function () {
  92304. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92305. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92306. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92307. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92308. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92309. GLTF2.ArrayItem.Assign(this._gltf.images);
  92310. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92311. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92312. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92313. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92314. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92315. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92316. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92317. if (this._gltf.nodes) {
  92318. var nodeParents = {};
  92319. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92320. var node = _a[_i];
  92321. if (node.children) {
  92322. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92323. var index = _c[_b];
  92324. nodeParents[index] = node._index;
  92325. }
  92326. }
  92327. }
  92328. var rootNode = this._createRootNode();
  92329. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92330. var node = _e[_d];
  92331. var parentIndex = nodeParents[node._index];
  92332. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92333. }
  92334. }
  92335. };
  92336. GLTFLoader.prototype._checkExtensions = function () {
  92337. if (this._gltf.extensionsRequired) {
  92338. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92339. var name_2 = _a[_i];
  92340. var extension = this._extensions[name_2];
  92341. if (!extension || !extension.enabled) {
  92342. throw new Error("Require extension " + name_2 + " is not available");
  92343. }
  92344. }
  92345. }
  92346. };
  92347. GLTFLoader.prototype._createRootNode = function () {
  92348. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92349. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92350. switch (this.coordinateSystemMode) {
  92351. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92352. if (!this._babylonScene.useRightHandedSystem) {
  92353. rootNode.rotation = [0, 1, 0, 0];
  92354. rootNode.scale = [1, 1, -1];
  92355. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92356. }
  92357. break;
  92358. }
  92359. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92360. this._babylonScene.useRightHandedSystem = true;
  92361. break;
  92362. }
  92363. default: {
  92364. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92365. }
  92366. }
  92367. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92368. return rootNode;
  92369. };
  92370. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92371. var promises = new Array();
  92372. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92373. var node = nodes_1[_i];
  92374. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92375. }
  92376. promises.push(this._loadAnimationsAsync());
  92377. return Promise.all(promises).then(function () { });
  92378. };
  92379. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92380. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92381. if (promise) {
  92382. return promise;
  92383. }
  92384. var promises = new Array();
  92385. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92386. var index = _a[_i];
  92387. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92388. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92389. }
  92390. promises.push(this._loadAnimationsAsync());
  92391. return Promise.all(promises).then(function () { });
  92392. };
  92393. GLTFLoader.prototype._getMeshes = function () {
  92394. var meshes = new Array();
  92395. // Root mesh is always first.
  92396. meshes.push(this._rootBabylonMesh);
  92397. var nodes = this._gltf.nodes;
  92398. if (nodes) {
  92399. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92400. var node = nodes_2[_i];
  92401. if (node._babylonMesh) {
  92402. meshes.push(node._babylonMesh);
  92403. }
  92404. if (node._primitiveBabylonMeshes) {
  92405. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92406. var babylonMesh = _b[_a];
  92407. meshes.push(babylonMesh);
  92408. }
  92409. }
  92410. }
  92411. }
  92412. return meshes;
  92413. };
  92414. GLTFLoader.prototype._getSkeletons = function () {
  92415. var skeletons = new Array();
  92416. var skins = this._gltf.skins;
  92417. if (skins) {
  92418. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92419. var skin = skins_1[_i];
  92420. if (skin._babylonSkeleton) {
  92421. skeletons.push(skin._babylonSkeleton);
  92422. }
  92423. }
  92424. }
  92425. return skeletons;
  92426. };
  92427. GLTFLoader.prototype._startAnimations = function () {
  92428. var animations = this._gltf.animations;
  92429. if (!animations) {
  92430. return;
  92431. }
  92432. switch (this.animationStartMode) {
  92433. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92434. // do nothing
  92435. break;
  92436. }
  92437. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92438. var animation = animations[0];
  92439. animation._babylonAnimationGroup.start(true);
  92440. break;
  92441. }
  92442. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92443. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92444. var animation = animations_1[_i];
  92445. animation._babylonAnimationGroup.start(true);
  92446. }
  92447. break;
  92448. }
  92449. default: {
  92450. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92451. return;
  92452. }
  92453. }
  92454. };
  92455. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92456. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92457. if (promise) {
  92458. return promise;
  92459. }
  92460. if (node._babylonMesh) {
  92461. throw new Error(context + ": Invalid recursive node hierarchy");
  92462. }
  92463. var promises = new Array();
  92464. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92465. node._babylonMesh = babylonMesh;
  92466. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92467. node._babylonAnimationTargets.push(babylonMesh);
  92468. GLTFLoader._LoadTransform(node, babylonMesh);
  92469. if (node.mesh != undefined) {
  92470. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92471. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92472. }
  92473. if (node.children) {
  92474. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92475. var index = _a[_i];
  92476. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92477. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92478. }
  92479. }
  92480. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92481. return Promise.all(promises).then(function () { });
  92482. };
  92483. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92484. // TODO: instancing
  92485. var promises = new Array();
  92486. var primitives = mesh.primitives;
  92487. if (!primitives || primitives.length === 0) {
  92488. throw new Error(context + ": Primitives are missing");
  92489. }
  92490. GLTF2.ArrayItem.Assign(primitives);
  92491. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92492. var primitive = primitives_1[_i];
  92493. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92494. }
  92495. if (node.skin != undefined) {
  92496. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92497. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92498. }
  92499. return Promise.all(promises).then(function () {
  92500. if (node._primitiveBabylonMeshes) {
  92501. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92502. var primitiveBabylonMesh = _a[_i];
  92503. primitiveBabylonMesh._refreshBoundingInfo(true);
  92504. }
  92505. }
  92506. });
  92507. };
  92508. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92509. var _this = this;
  92510. var promises = new Array();
  92511. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92512. babylonMesh.setEnabled(false);
  92513. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92514. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92515. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92516. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92517. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92518. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92519. }));
  92520. if (primitive.material == undefined) {
  92521. babylonMesh.material = this._getDefaultMaterial();
  92522. }
  92523. else {
  92524. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92525. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  92526. }
  92527. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92528. return Promise.all(promises).then(function () {
  92529. babylonMesh.setEnabled(true);
  92530. });
  92531. };
  92532. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92533. var _this = this;
  92534. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92535. if (promise) {
  92536. return promise;
  92537. }
  92538. var attributes = primitive.attributes;
  92539. if (!attributes) {
  92540. throw new Error(context + ": Attributes are missing");
  92541. }
  92542. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92543. // TODO: handle other primitive modes
  92544. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92545. }
  92546. var promises = new Array();
  92547. var babylonVertexData = new BABYLON.VertexData();
  92548. if (primitive.indices == undefined) {
  92549. var positionAccessorIndex = attributes["POSITION"];
  92550. if (positionAccessorIndex != undefined) {
  92551. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92552. babylonVertexData.indices = new Uint32Array(accessor.count);
  92553. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92554. babylonVertexData.indices[i] = i;
  92555. }
  92556. }
  92557. }
  92558. else {
  92559. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92560. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92561. babylonVertexData.indices = data;
  92562. }));
  92563. }
  92564. var loadAttribute = function (attribute, kind) {
  92565. if (attributes[attribute] == undefined) {
  92566. return;
  92567. }
  92568. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92569. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92570. babylonMesh._delayInfo.push(kind);
  92571. }
  92572. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92573. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92574. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92575. if (attribute === "COLOR_0") {
  92576. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92577. babylonMesh.hasVertexAlpha = true;
  92578. if (accessor.type === "VEC3") {
  92579. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92580. }
  92581. }
  92582. babylonVertexData.set(attributeData, kind);
  92583. }));
  92584. };
  92585. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92586. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92587. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92588. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92589. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92590. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92591. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92592. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92593. return Promise.all(promises).then(function () {
  92594. return babylonVertexData;
  92595. });
  92596. };
  92597. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92598. if (!primitive.targets) {
  92599. return;
  92600. }
  92601. if (node._numMorphTargets == undefined) {
  92602. node._numMorphTargets = primitive.targets.length;
  92603. }
  92604. else if (primitive.targets.length !== node._numMorphTargets) {
  92605. throw new Error(context + ": Primitives do not have the same number of targets");
  92606. }
  92607. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92608. for (var index = 0; index < primitive.targets.length; index++) {
  92609. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92610. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92611. // TODO: tell the target whether it has positions, normals, tangents
  92612. }
  92613. };
  92614. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92615. if (!primitive.targets) {
  92616. return Promise.resolve();
  92617. }
  92618. var promises = new Array();
  92619. var morphTargetManager = babylonMesh.morphTargetManager;
  92620. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92621. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92622. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92623. }
  92624. return Promise.all(promises).then(function () { });
  92625. };
  92626. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92627. var _this = this;
  92628. var promises = new Array();
  92629. var loadAttribute = function (attribute, setData) {
  92630. if (attributes[attribute] == undefined) {
  92631. return;
  92632. }
  92633. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92634. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92635. setData(data);
  92636. }));
  92637. };
  92638. loadAttribute("POSITION", function (data) {
  92639. if (babylonVertexData.positions) {
  92640. for (var i = 0; i < data.length; i++) {
  92641. data[i] += babylonVertexData.positions[i];
  92642. }
  92643. babylonMorphTarget.setPositions(data);
  92644. }
  92645. });
  92646. loadAttribute("NORMAL", function (data) {
  92647. if (babylonVertexData.normals) {
  92648. for (var i = 0; i < data.length; i++) {
  92649. data[i] += babylonVertexData.normals[i];
  92650. }
  92651. babylonMorphTarget.setNormals(data);
  92652. }
  92653. });
  92654. loadAttribute("TANGENT", function (data) {
  92655. if (babylonVertexData.tangents) {
  92656. // Tangent data for morph targets is stored as xyz delta.
  92657. // The vertexData.tangent is stored as xyzw.
  92658. // So we need to skip every fourth vertexData.tangent.
  92659. for (var i = 0, j = 0; i < data.length; i++) {
  92660. data[i] += babylonVertexData.tangents[j++];
  92661. if ((i + 1) % 3 == 0) {
  92662. j++;
  92663. }
  92664. }
  92665. babylonMorphTarget.setTangents(data);
  92666. }
  92667. });
  92668. return Promise.all(promises).then(function () { });
  92669. };
  92670. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92671. if (accessor.componentType == 5126 /* FLOAT */) {
  92672. return data;
  92673. }
  92674. var factor = 1;
  92675. if (accessor.normalized) {
  92676. switch (accessor.componentType) {
  92677. case 5121 /* UNSIGNED_BYTE */: {
  92678. factor = 1 / 255;
  92679. break;
  92680. }
  92681. case 5123 /* UNSIGNED_SHORT */: {
  92682. factor = 1 / 65535;
  92683. break;
  92684. }
  92685. default: {
  92686. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92687. }
  92688. }
  92689. }
  92690. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92691. for (var i = 0; i < result.length; i++) {
  92692. result[i] = data[i] * factor;
  92693. }
  92694. return result;
  92695. };
  92696. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92697. var result = new Float32Array(data.length / 3 * 4);
  92698. var offset = 0;
  92699. for (var i = 0; i < result.length; i++) {
  92700. if ((i + 1) % 4 === 0) {
  92701. result[i] = 1;
  92702. }
  92703. else {
  92704. result[i] = data[offset++];
  92705. }
  92706. }
  92707. return result;
  92708. };
  92709. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92710. var position = BABYLON.Vector3.Zero();
  92711. var rotation = BABYLON.Quaternion.Identity();
  92712. var scaling = BABYLON.Vector3.One();
  92713. if (node.matrix) {
  92714. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92715. matrix.decompose(scaling, rotation, position);
  92716. }
  92717. else {
  92718. if (node.translation)
  92719. position = BABYLON.Vector3.FromArray(node.translation);
  92720. if (node.rotation)
  92721. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92722. if (node.scale)
  92723. scaling = BABYLON.Vector3.FromArray(node.scale);
  92724. }
  92725. babylonNode.position = position;
  92726. babylonNode.rotationQuaternion = rotation;
  92727. babylonNode.scaling = scaling;
  92728. };
  92729. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92730. var _this = this;
  92731. var assignSkeleton = function () {
  92732. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92733. var babylonMesh = _a[_i];
  92734. babylonMesh.skeleton = skin._babylonSkeleton;
  92735. }
  92736. node._babylonMesh.parent = _this._rootBabylonMesh;
  92737. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92738. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92739. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92740. };
  92741. if (skin._loaded) {
  92742. return skin._loaded.then(function () {
  92743. assignSkeleton();
  92744. });
  92745. }
  92746. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  92747. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  92748. var skeletonId = "skeleton" + skin._index;
  92749. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  92750. skin._babylonSkeleton = babylonSkeleton;
  92751. _this._loadBones(context, skin, inverseBindMatricesData);
  92752. assignSkeleton();
  92753. }));
  92754. };
  92755. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  92756. if (skin.inverseBindMatrices == undefined) {
  92757. return Promise.resolve(null);
  92758. }
  92759. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  92760. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92761. return data;
  92762. });
  92763. };
  92764. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  92765. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  92766. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92767. node._babylonAnimationTargets.push(babylonBone);
  92768. return babylonBone;
  92769. };
  92770. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  92771. var babylonBones = {};
  92772. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  92773. var index = _a[_i];
  92774. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  92775. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  92776. }
  92777. };
  92778. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  92779. var babylonBone = babylonBones[node._index];
  92780. if (babylonBone) {
  92781. return babylonBone;
  92782. }
  92783. var boneIndex = skin.joints.indexOf(node._index);
  92784. var baseMatrix = BABYLON.Matrix.Identity();
  92785. if (inverseBindMatricesData && boneIndex !== -1) {
  92786. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  92787. baseMatrix.invertToRef(baseMatrix);
  92788. }
  92789. var babylonParentBone = null;
  92790. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  92791. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  92792. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  92793. }
  92794. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  92795. babylonBones[node._index] = babylonBone;
  92796. return babylonBone;
  92797. };
  92798. GLTFLoader.prototype._getNodeMatrix = function (node) {
  92799. return node.matrix ?
  92800. BABYLON.Matrix.FromArray(node.matrix) :
  92801. 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());
  92802. };
  92803. GLTFLoader.prototype._loadAnimationsAsync = function () {
  92804. var animations = this._gltf.animations;
  92805. if (!animations) {
  92806. return Promise.resolve();
  92807. }
  92808. var promises = new Array();
  92809. for (var index = 0; index < animations.length; index++) {
  92810. var animation = animations[index];
  92811. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  92812. }
  92813. return Promise.all(promises).then(function () { });
  92814. };
  92815. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  92816. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  92817. animation._babylonAnimationGroup = babylonAnimationGroup;
  92818. var promises = new Array();
  92819. GLTF2.ArrayItem.Assign(animation.channels);
  92820. GLTF2.ArrayItem.Assign(animation.samplers);
  92821. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  92822. var channel = _a[_i];
  92823. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  92824. }
  92825. return Promise.all(promises).then(function () {
  92826. babylonAnimationGroup.normalize();
  92827. });
  92828. };
  92829. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  92830. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  92831. if (!targetNode._babylonMesh) {
  92832. return Promise.resolve();
  92833. }
  92834. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  92835. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  92836. var targetPath;
  92837. var animationType;
  92838. switch (channel.target.path) {
  92839. case "translation" /* TRANSLATION */: {
  92840. targetPath = "position";
  92841. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92842. break;
  92843. }
  92844. case "rotation" /* ROTATION */: {
  92845. targetPath = "rotationQuaternion";
  92846. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92847. break;
  92848. }
  92849. case "scale" /* SCALE */: {
  92850. targetPath = "scaling";
  92851. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92852. break;
  92853. }
  92854. case "weights" /* WEIGHTS */: {
  92855. targetPath = "influence";
  92856. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  92857. break;
  92858. }
  92859. default: {
  92860. throw new Error(context + ": Invalid target path " + channel.target.path);
  92861. }
  92862. }
  92863. var outputBufferOffset = 0;
  92864. var getNextOutputValue;
  92865. switch (targetPath) {
  92866. case "position": {
  92867. getNextOutputValue = function () {
  92868. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92869. outputBufferOffset += 3;
  92870. return value;
  92871. };
  92872. break;
  92873. }
  92874. case "rotationQuaternion": {
  92875. getNextOutputValue = function () {
  92876. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  92877. outputBufferOffset += 4;
  92878. return value;
  92879. };
  92880. break;
  92881. }
  92882. case "scaling": {
  92883. getNextOutputValue = function () {
  92884. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92885. outputBufferOffset += 3;
  92886. return value;
  92887. };
  92888. break;
  92889. }
  92890. case "influence": {
  92891. getNextOutputValue = function () {
  92892. var value = new Array(targetNode._numMorphTargets);
  92893. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  92894. value[i] = data.output[outputBufferOffset++];
  92895. }
  92896. return value;
  92897. };
  92898. break;
  92899. }
  92900. }
  92901. var getNextKey;
  92902. switch (data.interpolation) {
  92903. case "STEP" /* STEP */: {
  92904. getNextKey = function (frameIndex) { return ({
  92905. frame: data.input[frameIndex],
  92906. value: getNextOutputValue(),
  92907. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  92908. }); };
  92909. break;
  92910. }
  92911. case "LINEAR" /* LINEAR */: {
  92912. getNextKey = function (frameIndex) { return ({
  92913. frame: data.input[frameIndex],
  92914. value: getNextOutputValue()
  92915. }); };
  92916. break;
  92917. }
  92918. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92919. getNextKey = function (frameIndex) { return ({
  92920. frame: data.input[frameIndex],
  92921. inTangent: getNextOutputValue(),
  92922. value: getNextOutputValue(),
  92923. outTangent: getNextOutputValue()
  92924. }); };
  92925. break;
  92926. }
  92927. }
  92928. var keys;
  92929. if (data.input.length === 1) {
  92930. var key = getNextKey(0);
  92931. keys = [
  92932. { frame: key.frame, value: key.value },
  92933. { frame: key.frame + 1, value: key.value }
  92934. ];
  92935. }
  92936. else {
  92937. keys = new Array(data.input.length);
  92938. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  92939. keys[frameIndex] = getNextKey(frameIndex);
  92940. }
  92941. }
  92942. if (targetPath === "influence") {
  92943. var _loop_1 = function (targetIndex) {
  92944. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92945. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92946. babylonAnimation.setKeys(keys.map(function (key) { return ({
  92947. frame: key.frame,
  92948. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  92949. value: key.value[targetIndex],
  92950. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  92951. }); }));
  92952. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92953. var babylonMesh = _a[_i];
  92954. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  92955. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  92956. }
  92957. };
  92958. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  92959. _loop_1(targetIndex);
  92960. }
  92961. }
  92962. else {
  92963. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92964. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92965. babylonAnimation.setKeys(keys);
  92966. if (targetNode._babylonAnimationTargets) {
  92967. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  92968. var target = _a[_i];
  92969. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  92970. }
  92971. }
  92972. }
  92973. });
  92974. };
  92975. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  92976. if (sampler._data) {
  92977. return sampler._data;
  92978. }
  92979. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  92980. switch (interpolation) {
  92981. case "STEP" /* STEP */:
  92982. case "LINEAR" /* LINEAR */:
  92983. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92984. break;
  92985. }
  92986. default: {
  92987. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  92988. }
  92989. }
  92990. var inputData;
  92991. var outputData;
  92992. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  92993. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  92994. sampler._data = Promise.all([
  92995. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  92996. inputData = data;
  92997. }),
  92998. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  92999. outputData = data;
  93000. })
  93001. ]).then(function () {
  93002. return {
  93003. input: inputData,
  93004. interpolation: interpolation,
  93005. output: outputData,
  93006. };
  93007. });
  93008. return sampler._data;
  93009. };
  93010. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93011. if (buffer._data) {
  93012. return buffer._data;
  93013. }
  93014. if (!buffer.uri) {
  93015. throw new Error(context + ": Uri is missing");
  93016. }
  93017. buffer._data = this._loadUriAsync(context, buffer.uri);
  93018. return buffer._data;
  93019. };
  93020. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93021. if (bufferView._data) {
  93022. return bufferView._data;
  93023. }
  93024. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93025. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93026. try {
  93027. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93028. }
  93029. catch (e) {
  93030. throw new Error(context + ": " + e.message);
  93031. }
  93032. });
  93033. return bufferView._data;
  93034. };
  93035. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93036. var _this = this;
  93037. if (accessor.sparse) {
  93038. throw new Error(context + ": Sparse accessors are not currently supported");
  93039. }
  93040. if (accessor._data) {
  93041. return accessor._data;
  93042. }
  93043. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93044. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93045. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93046. var byteOffset = accessor.byteOffset || 0;
  93047. var byteStride = bufferView.byteStride;
  93048. if (byteStride === 0) {
  93049. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93050. }
  93051. try {
  93052. switch (accessor.componentType) {
  93053. case 5120 /* BYTE */: {
  93054. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93055. }
  93056. case 5121 /* UNSIGNED_BYTE */: {
  93057. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93058. }
  93059. case 5122 /* SHORT */: {
  93060. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93061. }
  93062. case 5123 /* UNSIGNED_SHORT */: {
  93063. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93064. }
  93065. case 5125 /* UNSIGNED_INT */: {
  93066. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93067. }
  93068. case 5126 /* FLOAT */: {
  93069. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93070. }
  93071. default: {
  93072. throw new Error(context + ": Invalid component type " + accessor.componentType);
  93073. }
  93074. }
  93075. }
  93076. catch (e) {
  93077. throw new Error(context + ": " + e);
  93078. }
  93079. });
  93080. return accessor._data;
  93081. };
  93082. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93083. byteOffset += data.byteOffset;
  93084. var targetLength = count * numComponents;
  93085. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93086. return new typedArray(data.buffer, byteOffset, targetLength);
  93087. }
  93088. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93089. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93090. var targetBuffer = new typedArray(targetLength);
  93091. var sourceIndex = 0;
  93092. var targetIndex = 0;
  93093. while (targetIndex < targetLength) {
  93094. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93095. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93096. targetIndex++;
  93097. }
  93098. sourceIndex += elementStride;
  93099. }
  93100. return targetBuffer;
  93101. };
  93102. GLTFLoader.prototype._getDefaultMaterial = function () {
  93103. var id = "__gltf_default";
  93104. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93105. if (!babylonMaterial) {
  93106. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93107. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93108. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93109. babylonMaterial.metallic = 1;
  93110. babylonMaterial.roughness = 1;
  93111. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93112. }
  93113. return babylonMaterial;
  93114. };
  93115. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93116. var promises = new Array();
  93117. var babylonMaterial = material._babylonMaterial;
  93118. // Ensure metallic workflow
  93119. babylonMaterial.metallic = 1;
  93120. babylonMaterial.roughness = 1;
  93121. var properties = material.pbrMetallicRoughness;
  93122. if (properties) {
  93123. if (properties.baseColorFactor) {
  93124. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93125. babylonMaterial.alpha = properties.baseColorFactor[3];
  93126. }
  93127. else {
  93128. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93129. }
  93130. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93131. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93132. if (properties.baseColorTexture) {
  93133. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93134. babylonMaterial.albedoTexture = texture;
  93135. }));
  93136. }
  93137. if (properties.metallicRoughnessTexture) {
  93138. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93139. babylonMaterial.metallicTexture = texture;
  93140. }));
  93141. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93142. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93143. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93144. }
  93145. }
  93146. this._loadMaterialAlphaProperties(context, material);
  93147. return Promise.all(promises).then(function () { });
  93148. };
  93149. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93150. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  93151. if (promise) {
  93152. return promise;
  93153. }
  93154. material._babylonMeshes = material._babylonMeshes || [];
  93155. material._babylonMeshes.push(babylonMesh);
  93156. if (material._loaded) {
  93157. babylonMesh.material = material._babylonMaterial;
  93158. return material._loaded;
  93159. }
  93160. var promises = new Array();
  93161. var babylonMaterial = this._createMaterial(material);
  93162. material._babylonMaterial = babylonMaterial;
  93163. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93164. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93165. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93166. babylonMesh.material = babylonMaterial;
  93167. return (material._loaded = Promise.all(promises).then(function () { }));
  93168. };
  93169. GLTFLoader.prototype._createMaterial = function (material) {
  93170. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93171. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93172. return babylonMaterial;
  93173. };
  93174. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93175. var promises = new Array();
  93176. var babylonMaterial = material._babylonMaterial;
  93177. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93178. if (material.doubleSided) {
  93179. babylonMaterial.backFaceCulling = false;
  93180. babylonMaterial.twoSidedLighting = true;
  93181. }
  93182. if (material.normalTexture) {
  93183. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93184. babylonMaterial.bumpTexture = texture;
  93185. }));
  93186. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93187. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93188. if (material.normalTexture.scale != undefined) {
  93189. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93190. }
  93191. }
  93192. if (material.occlusionTexture) {
  93193. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93194. babylonMaterial.ambientTexture = texture;
  93195. }));
  93196. babylonMaterial.useAmbientInGrayScale = true;
  93197. if (material.occlusionTexture.strength != undefined) {
  93198. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93199. }
  93200. }
  93201. if (material.emissiveTexture) {
  93202. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93203. babylonMaterial.emissiveTexture = texture;
  93204. }));
  93205. }
  93206. return Promise.all(promises).then(function () { });
  93207. };
  93208. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93209. var babylonMaterial = material._babylonMaterial;
  93210. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93211. switch (alphaMode) {
  93212. case "OPAQUE" /* OPAQUE */: {
  93213. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93214. break;
  93215. }
  93216. case "MASK" /* MASK */: {
  93217. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93218. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93219. if (babylonMaterial.alpha) {
  93220. if (babylonMaterial.alpha === 0) {
  93221. babylonMaterial.alphaCutOff = 1;
  93222. }
  93223. else {
  93224. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93225. }
  93226. babylonMaterial.alpha = 1;
  93227. }
  93228. if (babylonMaterial.albedoTexture) {
  93229. babylonMaterial.albedoTexture.hasAlpha = true;
  93230. }
  93231. break;
  93232. }
  93233. case "BLEND" /* BLEND */: {
  93234. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93235. if (babylonMaterial.albedoTexture) {
  93236. babylonMaterial.albedoTexture.hasAlpha = true;
  93237. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93238. }
  93239. break;
  93240. }
  93241. default: {
  93242. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  93243. }
  93244. }
  93245. };
  93246. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93247. var _this = this;
  93248. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93249. context = "#/textures/" + textureInfo.index;
  93250. var promises = new Array();
  93251. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93252. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93253. var deferred = new BABYLON.Deferred();
  93254. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93255. if (!_this._disposed) {
  93256. deferred.resolve();
  93257. }
  93258. }, function (message, exception) {
  93259. if (!_this._disposed) {
  93260. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  93261. }
  93262. });
  93263. promises.push(deferred.promise);
  93264. babylonTexture.name = texture.name || "texture" + texture._index;
  93265. babylonTexture.wrapU = samplerData.wrapU;
  93266. babylonTexture.wrapV = samplerData.wrapV;
  93267. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93268. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93269. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93270. babylonTexture.updateURL(objectURL);
  93271. }));
  93272. assign(babylonTexture);
  93273. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93274. return Promise.all(promises).then(function () { });
  93275. };
  93276. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93277. if (!sampler._data) {
  93278. sampler._data = {
  93279. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93280. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93281. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93282. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93283. };
  93284. }
  93285. ;
  93286. return sampler._data;
  93287. };
  93288. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93289. if (image._objectURL) {
  93290. return image._objectURL;
  93291. }
  93292. var promise;
  93293. if (image.uri) {
  93294. promise = this._loadUriAsync(context, image.uri);
  93295. }
  93296. else {
  93297. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93298. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93299. }
  93300. image._objectURL = promise.then(function (data) {
  93301. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93302. });
  93303. return image._objectURL;
  93304. };
  93305. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93306. var _this = this;
  93307. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93308. if (promise) {
  93309. return promise;
  93310. }
  93311. if (!GLTFLoader._ValidateUri(uri)) {
  93312. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93313. }
  93314. if (BABYLON.Tools.IsBase64(uri)) {
  93315. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93316. }
  93317. return new Promise(function (resolve, reject) {
  93318. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93319. if (!_this._disposed) {
  93320. resolve(new Uint8Array(data));
  93321. }
  93322. }, function (event) {
  93323. if (!_this._disposed) {
  93324. try {
  93325. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93326. request._lengthComputable = event.lengthComputable;
  93327. request._loaded = event.loaded;
  93328. request._total = event.total;
  93329. _this._onProgress();
  93330. }
  93331. }
  93332. catch (e) {
  93333. reject(e);
  93334. }
  93335. }
  93336. }, _this._babylonScene.database, true, function (request, exception) {
  93337. if (!_this._disposed) {
  93338. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93339. }
  93340. });
  93341. _this._requests.push(request);
  93342. });
  93343. };
  93344. GLTFLoader.prototype._onProgress = function () {
  93345. if (!this._progressCallback) {
  93346. return;
  93347. }
  93348. var lengthComputable = true;
  93349. var loaded = 0;
  93350. var total = 0;
  93351. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93352. var request = _a[_i];
  93353. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93354. return;
  93355. }
  93356. lengthComputable = lengthComputable && request._lengthComputable;
  93357. loaded += request._loaded;
  93358. total += request._total;
  93359. }
  93360. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93361. };
  93362. GLTFLoader._GetProperty = function (context, array, index) {
  93363. if (!array || index == undefined || !array[index]) {
  93364. throw new Error(context + ": Failed to find index " + index);
  93365. }
  93366. return array[index];
  93367. };
  93368. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93369. // Set defaults if undefined
  93370. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93371. switch (mode) {
  93372. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93373. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93374. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93375. default:
  93376. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93377. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93378. }
  93379. };
  93380. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93381. // Set defaults if undefined
  93382. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93383. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93384. if (magFilter === 9729 /* LINEAR */) {
  93385. switch (minFilter) {
  93386. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93387. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93388. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93389. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93390. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93391. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93392. default:
  93393. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93394. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93395. }
  93396. }
  93397. else {
  93398. if (magFilter !== 9728 /* NEAREST */) {
  93399. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93400. }
  93401. switch (minFilter) {
  93402. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93403. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93404. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93405. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93406. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93407. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93408. default:
  93409. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93410. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93411. }
  93412. }
  93413. };
  93414. GLTFLoader._GetNumComponents = function (context, type) {
  93415. switch (type) {
  93416. case "SCALAR": return 1;
  93417. case "VEC2": return 2;
  93418. case "VEC3": return 3;
  93419. case "VEC4": return 4;
  93420. case "MAT2": return 4;
  93421. case "MAT3": return 9;
  93422. case "MAT4": return 16;
  93423. }
  93424. throw new Error(context + ": Invalid type " + type);
  93425. };
  93426. GLTFLoader._ValidateUri = function (uri) {
  93427. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93428. };
  93429. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93430. var promises = new Array();
  93431. if (this._gltf.materials) {
  93432. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93433. var material = _a[_i];
  93434. var babylonMaterial = material._babylonMaterial;
  93435. var babylonMeshes = material._babylonMeshes;
  93436. if (babylonMaterial && babylonMeshes) {
  93437. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93438. var babylonMesh = babylonMeshes_1[_b];
  93439. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93440. if (this.useClipPlane) {
  93441. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93442. }
  93443. }
  93444. }
  93445. }
  93446. }
  93447. return Promise.all(promises).then(function () { });
  93448. };
  93449. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93450. var promises = new Array();
  93451. var lights = this._babylonScene.lights;
  93452. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93453. var light = lights_1[_i];
  93454. var generator = light.getShadowGenerator();
  93455. if (generator) {
  93456. promises.push(generator.forceCompilationAsync());
  93457. }
  93458. }
  93459. return Promise.all(promises).then(function () { });
  93460. };
  93461. GLTFLoader.prototype._clear = function () {
  93462. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93463. var request = _a[_i];
  93464. request.abort();
  93465. }
  93466. this._requests.length = 0;
  93467. if (this._gltf && this._gltf.images) {
  93468. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93469. var image = _c[_b];
  93470. if (image._objectURL) {
  93471. image._objectURL.then(function (value) {
  93472. URL.revokeObjectURL(value);
  93473. });
  93474. image._objectURL = undefined;
  93475. }
  93476. }
  93477. }
  93478. delete this._gltf;
  93479. delete this._babylonScene;
  93480. this._completePromises.length = 0;
  93481. for (var name_3 in this._extensions) {
  93482. this._extensions[name_3].dispose();
  93483. }
  93484. this._extensions = {};
  93485. delete this._rootBabylonMesh;
  93486. delete this._progressCallback;
  93487. this.onMeshLoadedObservable.clear();
  93488. this.onTextureLoadedObservable.clear();
  93489. this.onMaterialLoadedObservable.clear();
  93490. };
  93491. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93492. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93493. var name_4 = _a[_i];
  93494. var extension = this._extensions[name_4];
  93495. if (extension.enabled) {
  93496. var promise = actionAsync(extension);
  93497. if (promise) {
  93498. return promise;
  93499. }
  93500. }
  93501. }
  93502. return null;
  93503. };
  93504. GLTFLoader._Names = new Array();
  93505. GLTFLoader._Factories = {};
  93506. return GLTFLoader;
  93507. }());
  93508. GLTF2.GLTFLoader = GLTFLoader;
  93509. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93510. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93511. })(BABYLON || (BABYLON = {}));
  93512. //# sourceMappingURL=babylon.glTFLoader.js.map
  93513. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93514. var BABYLON;
  93515. (function (BABYLON) {
  93516. var GLTF2;
  93517. (function (GLTF2) {
  93518. var GLTFLoaderExtension = /** @class */ (function () {
  93519. function GLTFLoaderExtension(loader) {
  93520. this.enabled = true;
  93521. this._loader = loader;
  93522. }
  93523. GLTFLoaderExtension.prototype.dispose = function () {
  93524. delete this._loader;
  93525. };
  93526. // #region Overridable Methods
  93527. /** Override this method to modify the default behavior for loading scenes. */
  93528. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93529. /** Override this method to modify the default behavior for loading nodes. */
  93530. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93531. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93532. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93533. /** Override this method to modify the default behavior for loading materials. */
  93534. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  93535. /** Override this method to modify the default behavior for loading uris. */
  93536. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93537. // #endregion
  93538. /** Helper method called by a loader extension to load an glTF extension. */
  93539. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93540. if (!property.extensions) {
  93541. return null;
  93542. }
  93543. var extensions = property.extensions;
  93544. var extension = extensions[this.name];
  93545. if (!extension) {
  93546. return null;
  93547. }
  93548. // Clear out the extension before executing the action to avoid recursing into the same property.
  93549. delete extensions[this.name];
  93550. try {
  93551. return actionAsync(context + "/extensions/" + this.name, extension);
  93552. }
  93553. finally {
  93554. // Restore the extension after executing the action.
  93555. extensions[this.name] = extension;
  93556. }
  93557. };
  93558. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93559. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93560. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93561. };
  93562. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93563. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93564. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93565. };
  93566. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93567. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93568. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93569. };
  93570. /** Helper method called by the loader to allow extensions to override loading materials. */
  93571. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  93572. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  93573. };
  93574. /** Helper method called by the loader to allow extensions to override loading uris. */
  93575. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93576. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93577. };
  93578. return GLTFLoaderExtension;
  93579. }());
  93580. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93581. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93582. })(BABYLON || (BABYLON = {}));
  93583. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93584. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93585. var BABYLON;
  93586. (function (BABYLON) {
  93587. var GLTF2;
  93588. (function (GLTF2) {
  93589. var Extensions;
  93590. (function (Extensions) {
  93591. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93592. var NAME = "MSFT_lod";
  93593. var MSFT_lod = /** @class */ (function (_super) {
  93594. __extends(MSFT_lod, _super);
  93595. function MSFT_lod() {
  93596. var _this = _super !== null && _super.apply(this, arguments) || this;
  93597. _this.name = NAME;
  93598. /**
  93599. * Maximum number of LODs to load, starting from the lowest LOD.
  93600. */
  93601. _this.maxLODsToLoad = Number.MAX_VALUE;
  93602. _this._loadingNodeLOD = null;
  93603. _this._loadNodeSignals = {};
  93604. _this._loadingMaterialLOD = null;
  93605. _this._loadMaterialSignals = {};
  93606. return _this;
  93607. }
  93608. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93609. var _this = this;
  93610. return this._loadExtensionAsync(context, node, function (context, extension) {
  93611. var firstPromise;
  93612. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93613. var _loop_1 = function (indexLOD) {
  93614. var nodeLOD = nodeLODs[indexLOD];
  93615. if (indexLOD !== 0) {
  93616. _this._loadingNodeLOD = nodeLOD;
  93617. if (!_this._loadNodeSignals[nodeLOD._index]) {
  93618. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93619. }
  93620. }
  93621. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93622. if (indexLOD !== 0) {
  93623. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93624. previousNodeLOD._babylonMesh.setEnabled(false);
  93625. }
  93626. if (indexLOD !== nodeLODs.length - 1) {
  93627. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93628. if (_this._loadNodeSignals[nodeIndex]) {
  93629. _this._loadNodeSignals[nodeIndex].resolve();
  93630. delete _this._loadNodeSignals[nodeIndex];
  93631. }
  93632. }
  93633. });
  93634. if (indexLOD === 0) {
  93635. firstPromise = promise;
  93636. }
  93637. else {
  93638. _this._loader._completePromises.push(promise);
  93639. _this._loadingNodeLOD = null;
  93640. }
  93641. };
  93642. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93643. _loop_1(indexLOD);
  93644. }
  93645. return firstPromise;
  93646. });
  93647. };
  93648. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93649. var _this = this;
  93650. // Don't load material LODs if already loading a node LOD.
  93651. if (this._loadingNodeLOD) {
  93652. return null;
  93653. }
  93654. return this._loadExtensionAsync(context, material, function (context, extension) {
  93655. var firstPromise;
  93656. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93657. var _loop_2 = function (indexLOD) {
  93658. var materialLOD = materialLODs[indexLOD];
  93659. if (indexLOD !== 0) {
  93660. _this._loadingMaterialLOD = materialLOD;
  93661. if (!_this._loadMaterialSignals[materialLOD._index]) {
  93662. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93663. }
  93664. }
  93665. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  93666. if (indexLOD !== materialLODs.length - 1) {
  93667. var materialIndex = materialLODs[indexLOD + 1]._index;
  93668. if (_this._loadMaterialSignals[materialIndex]) {
  93669. _this._loadMaterialSignals[materialIndex].resolve();
  93670. delete _this._loadMaterialSignals[materialIndex];
  93671. }
  93672. }
  93673. });
  93674. if (indexLOD === 0) {
  93675. firstPromise = promise;
  93676. }
  93677. else {
  93678. _this._loader._completePromises.push(promise);
  93679. _this._loadingMaterialLOD = null;
  93680. }
  93681. };
  93682. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93683. _loop_2(indexLOD);
  93684. }
  93685. return firstPromise;
  93686. });
  93687. };
  93688. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93689. var _this = this;
  93690. // Defer the loading of uris if loading a material or node LOD.
  93691. if (this._loadingMaterialLOD) {
  93692. var index = this._loadingMaterialLOD._index;
  93693. return this._loadMaterialSignals[index].promise.then(function () {
  93694. return _this._loader._loadUriAsync(context, uri);
  93695. });
  93696. }
  93697. else if (this._loadingNodeLOD) {
  93698. var index = this._loadingNodeLOD._index;
  93699. return this._loadNodeSignals[index].promise.then(function () {
  93700. return _this._loader._loadUriAsync(context, uri);
  93701. });
  93702. }
  93703. return null;
  93704. };
  93705. /**
  93706. * Gets an array of LOD properties from lowest to highest.
  93707. */
  93708. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93709. if (this.maxLODsToLoad <= 0) {
  93710. throw new Error("maxLODsToLoad must be greater than zero");
  93711. }
  93712. var properties = new Array();
  93713. for (var i = ids.length - 1; i >= 0; i--) {
  93714. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93715. if (properties.length === this.maxLODsToLoad) {
  93716. return properties;
  93717. }
  93718. }
  93719. properties.push(property);
  93720. return properties;
  93721. };
  93722. return MSFT_lod;
  93723. }(GLTF2.GLTFLoaderExtension));
  93724. Extensions.MSFT_lod = MSFT_lod;
  93725. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93726. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93727. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93728. })(BABYLON || (BABYLON = {}));
  93729. //# sourceMappingURL=MSFT_lod.js.map
  93730. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93731. var BABYLON;
  93732. (function (BABYLON) {
  93733. var GLTF2;
  93734. (function (GLTF2) {
  93735. var Extensions;
  93736. (function (Extensions) {
  93737. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93738. var NAME = "KHR_draco_mesh_compression";
  93739. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93740. __extends(KHR_draco_mesh_compression, _super);
  93741. function KHR_draco_mesh_compression(loader) {
  93742. var _this = _super.call(this, loader) || this;
  93743. _this.name = NAME;
  93744. _this._dracoCompression = null;
  93745. // Disable extension if decoder is not available.
  93746. if (!BABYLON.DracoCompression.DecoderUrl) {
  93747. _this.enabled = false;
  93748. }
  93749. return _this;
  93750. }
  93751. KHR_draco_mesh_compression.prototype.dispose = function () {
  93752. if (this._dracoCompression) {
  93753. this._dracoCompression.dispose();
  93754. }
  93755. _super.prototype.dispose.call(this);
  93756. };
  93757. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93758. var _this = this;
  93759. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  93760. if (primitive.mode != undefined) {
  93761. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  93762. primitive.mode !== 4 /* TRIANGLES */) {
  93763. throw new Error(context + ": Unsupported mode " + primitive.mode);
  93764. }
  93765. // TODO: handle triangle strips
  93766. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  93767. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  93768. }
  93769. }
  93770. var attributes = {};
  93771. var loadAttribute = function (name, kind) {
  93772. var uniqueId = extension.attributes[name];
  93773. if (uniqueId == undefined) {
  93774. return;
  93775. }
  93776. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93777. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93778. babylonMesh._delayInfo.push(kind);
  93779. }
  93780. attributes[kind] = uniqueId;
  93781. };
  93782. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93783. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93784. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93785. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93786. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93787. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93788. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93789. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93790. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  93791. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  93792. try {
  93793. if (!_this._dracoCompression) {
  93794. _this._dracoCompression = new BABYLON.DracoCompression();
  93795. }
  93796. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  93797. }
  93798. catch (e) {
  93799. throw new Error(context + ": " + e.message);
  93800. }
  93801. });
  93802. });
  93803. };
  93804. return KHR_draco_mesh_compression;
  93805. }(GLTF2.GLTFLoaderExtension));
  93806. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  93807. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  93808. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93809. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93810. })(BABYLON || (BABYLON = {}));
  93811. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  93812. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93813. var BABYLON;
  93814. (function (BABYLON) {
  93815. var GLTF2;
  93816. (function (GLTF2) {
  93817. var Extensions;
  93818. (function (Extensions) {
  93819. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  93820. var NAME = "KHR_materials_pbrSpecularGlossiness";
  93821. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  93822. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  93823. function KHR_materials_pbrSpecularGlossiness() {
  93824. var _this = _super !== null && _super.apply(this, arguments) || this;
  93825. _this.name = NAME;
  93826. return _this;
  93827. }
  93828. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93829. var _this = this;
  93830. return this._loadExtensionAsync(context, material, function (context, extension) {
  93831. material._babylonMeshes = material._babylonMeshes || [];
  93832. material._babylonMeshes.push(babylonMesh);
  93833. if (material._loaded) {
  93834. babylonMesh.material = material._babylonMaterial;
  93835. return material._loaded;
  93836. }
  93837. var promises = new Array();
  93838. var babylonMaterial = _this._loader._createMaterial(material);
  93839. material._babylonMaterial = babylonMaterial;
  93840. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  93841. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  93842. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93843. babylonMesh.material = babylonMaterial;
  93844. return (material._loaded = Promise.all(promises).then(function () { }));
  93845. });
  93846. };
  93847. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  93848. var promises = new Array();
  93849. var babylonMaterial = material._babylonMaterial;
  93850. if (properties.diffuseFactor) {
  93851. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  93852. babylonMaterial.alpha = properties.diffuseFactor[3];
  93853. }
  93854. else {
  93855. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93856. }
  93857. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  93858. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  93859. if (properties.diffuseTexture) {
  93860. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  93861. babylonMaterial.albedoTexture = texture;
  93862. }));
  93863. }
  93864. if (properties.specularGlossinessTexture) {
  93865. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  93866. babylonMaterial.reflectivityTexture = texture;
  93867. }));
  93868. babylonMaterial.reflectivityTexture.hasAlpha = true;
  93869. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  93870. }
  93871. loader._loadMaterialAlphaProperties(context, material);
  93872. return Promise.all(promises).then(function () { });
  93873. };
  93874. return KHR_materials_pbrSpecularGlossiness;
  93875. }(GLTF2.GLTFLoaderExtension));
  93876. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  93877. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  93878. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93879. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93880. })(BABYLON || (BABYLON = {}));
  93881. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  93882. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93883. var BABYLON;
  93884. (function (BABYLON) {
  93885. var GLTF2;
  93886. (function (GLTF2) {
  93887. var Extensions;
  93888. (function (Extensions) {
  93889. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  93890. var NAME = "KHR_lights";
  93891. var LightType;
  93892. (function (LightType) {
  93893. LightType["AMBIENT"] = "ambient";
  93894. LightType["DIRECTIONAL"] = "directional";
  93895. LightType["POINT"] = "point";
  93896. LightType["SPOT"] = "spot";
  93897. })(LightType || (LightType = {}));
  93898. var KHR_lights = /** @class */ (function (_super) {
  93899. __extends(KHR_lights, _super);
  93900. function KHR_lights() {
  93901. var _this = _super !== null && _super.apply(this, arguments) || this;
  93902. _this.name = NAME;
  93903. return _this;
  93904. }
  93905. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  93906. var _this = this;
  93907. return this._loadExtensionAsync(context, scene, function (context, extension) {
  93908. var promise = _this._loader._loadSceneAsync(context, scene);
  93909. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93910. if (light.type !== LightType.AMBIENT) {
  93911. throw new Error(context + ": Only ambient lights are allowed on a scene");
  93912. }
  93913. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  93914. return promise;
  93915. });
  93916. };
  93917. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  93918. var _this = this;
  93919. return this._loadExtensionAsync(context, node, function (context, extension) {
  93920. var promise = _this._loader._loadNodeAsync(context, node);
  93921. var babylonLight;
  93922. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93923. var name = node._babylonMesh.name;
  93924. switch (light.type) {
  93925. case LightType.AMBIENT: {
  93926. throw new Error(context + ": Ambient lights are not allowed on a node");
  93927. }
  93928. case LightType.DIRECTIONAL: {
  93929. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  93930. break;
  93931. }
  93932. case LightType.POINT: {
  93933. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  93934. break;
  93935. }
  93936. case LightType.SPOT: {
  93937. var spotLight = light;
  93938. // TODO: support inner and outer cone angles
  93939. //const innerConeAngle = spotLight.innerConeAngle || 0;
  93940. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  93941. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  93942. break;
  93943. }
  93944. default: {
  93945. throw new Error(context + ": Invalid light type " + light.type);
  93946. }
  93947. }
  93948. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  93949. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  93950. babylonLight.parent = node._babylonMesh;
  93951. return promise;
  93952. });
  93953. };
  93954. Object.defineProperty(KHR_lights.prototype, "_lights", {
  93955. get: function () {
  93956. var extensions = this._loader._gltf.extensions;
  93957. if (!extensions || !extensions[this.name]) {
  93958. throw new Error("#/extensions: " + this.name + " not found");
  93959. }
  93960. var extension = extensions[this.name];
  93961. return extension.lights;
  93962. },
  93963. enumerable: true,
  93964. configurable: true
  93965. });
  93966. return KHR_lights;
  93967. }(GLTF2.GLTFLoaderExtension));
  93968. Extensions.KHR_lights = KHR_lights;
  93969. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  93970. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93971. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93972. })(BABYLON || (BABYLON = {}));
  93973. //# sourceMappingURL=KHR_lights.js.map
  93974. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  93975. globalObject["BABYLON"] = BABYLON
  93976. return BABYLON;
  93977. });